在PybDn11中引用C++分配对象

2024-10-01 13:43:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个pypyd11的python绑定,引用了一个C++实例,该内存的处理在C++端。下面是一些示例代码:

import <pybind11/pybind11>

struct Dog {
    void bark() { printf("Bark!\n"); }
};

int main()
{
  auto dog = new Dog;
  Py_Initialize();
  initexample(); // Initialize the example python module for import 

  // TBD - Add binding  between dog and example.dog .

  PyRun_StringFlags("import example\n"
                    "\n"
                    "example.dog.bark()\n"  // Access the C++ allocated object dog.
                    , Py_file_input, main_dict, main_dict, NULL);
  Py_Finalize();
}

我一直在关注如何创建python ^ {< CD1>}和C++ ^ {< CD2>}变量之间的链接。在

我不能使用py:class_<Dog>.def(py::init<>()),因为这将分配Dog的新实例,这不是我想要的。在


Tags: the实例内存pyimportmainexampledict
3条回答

是的,我知道这个答案已经很晚了,但是之前提供的解决方案要么已经过时,要么以模糊的方式解决了问题。在

其他答案最大的问题是它们同时使用pybind和原始Python接口。使用pybind,您可以使用一个更简单、更好的解释器接口。在

遵循一个可以解决您的问题的实现。在

首先你会注意到我们使用了“embed.h”头文件。 这给了我们创建嵌入式模块的功能。在

再往下看,我们使用PYBIND11_EMBEDDED_MODULE,而不是常规的PYBIND11_MODULE或过时的{}。这是一个专门用于嵌入的宏。在

下一个有趣的部分是我们为结构定义的类型。除了Dog类型之外,我们还使用shared_ptr<Dog>。这对于处理实例至关重要。当main模块超出范围并开始清理时,它需要知道类/结构的类型是shared\ptr,否则会出现seg错误(原始指针在这里不可用,我个人认为这是一件好事)。在

最后要指出的是,我们实际上使用pybind11::scoped_interpreter类作为解释器,而不是使用原始Python接口。在

#include"pybind11\pybind11.h"
#include"pybind11\embed.h"

#include<iostream>

namespace py = pybind11;

struct Dog {
    void bark() { std::cout << "Bark!\n";  }
};

PYBIND11_EMBEDDED_MODULE(DogModule, m) {
    // look at the types! we have a shared_ptr<Dog>!
    py::class_<Dog, std::shared_ptr<Dog>>(m, "DogModule")
        .def("bark", &Dog::bark);
}


int main(int argc, char **argv) 
{
    // Create Python Interpreter
    py::scoped_interpreter guard;

    // Create Dog Instance
    std::shared_ptr<Dog> ptr = std::make_shared<Dog>();

    // Import the DogModule & Assign the instance to a name in python
    py::module main = py::module::import("__main__");
    main.import("DogModule");
    main.attr("dogInstance") = ptr;

    // Call the bark method from python
    py::exec("dogInstance.bark()");


    getchar();
    return 0;
}

我找到了自己问题的答案。诀窍是以下两个概念的结合:

  • 创建一个独立的函数来返回singleton。在
  • 在不绑定构造函数的情况下创建对singleton类的绑定。在

下面的方法说明了:

#include <Python.h>
#include <pybind11/pybind11.h>

namespace py = pybind11;
using namespace pybind11::literals;

// Singleton to wrap
struct Singleton
{
  Singleton() : x(0) {}

  int exchange(int n)  // set x and return the old value
  {
    std::swap(n, x);
    return n;
  }

  // Singleton reference 
  static Singleton& instance()
  {
    static Singleton just_one;
    return just_one;
  }

  int x;
};

PYBIND11_PLUGIN(example) {
    py::module m("example", "pybind11 example plugin");

    // Use this function to get access to the singleton
    m.def("get_instance",
          &Singleton::instance,
          py::return_value_policy::reference,
          "Get reference to the singleton");

    // Declare the singleton methods
    py::class_<Singleton>(m, "Singleton")
      // No init!
      .def("exchange",
           &Singleton::exchange,
           "n"_a,
           "Exchange and return the current value"
           )
      ;

    return m.ptr();
}

int main(int argc, char **argv)
{
  Py_Initialize();

  PyObject* main_module = PyImport_AddModule("__main__");
  PyObject* main_dict = PyModule_GetDict(main_module);

  initexample();

  // Call singleton from c++
  Singleton::instance().exchange(999);

  // Populate the example class with two static pointers to our instance.
  if (PyRun_StringFlags("import example\n"
                        "\n"
                        "example.s1 = example.get_instance()\n"
                        "example.s2 = example.get_instance()\n",
                        Py_file_input, main_dict, main_dict, NULL) == nullptr)
      PyErr_Print();

  // Test referencing the singleton references
  if (PyRun_StringFlags("from example import *\n"
                        "\n"
                        "for i in range(3):\n"
                        "  print s1.exchange(i*2+1)\n"
                        "  print s2.exchange(i*2+2)\n"
                        "print dir(s1)\n"
                        "print help(s1.exchange)\n"
                        ,
                        Py_file_input, main_dict, main_dict, NULL) == nullptr)
      PyErr_Print();

  Py_Finalize();

  exit(0);
}

由于pybind11v2.2.0还有另一种方法,使用自定义构造函数包装:python init方法不再需要调用c++构造函数。您可以让它直接返回c++singleton实例。在

在您的案例中,声明可能看起来像:

   // Declare the singleton methods
   py::class_<Singleton>(m, "Singleton")

      .def("init", [](){
          return std::unique_ptr<Singleton, py::nodelete>(&Singleton::instance());
      });

在python中:

^{pr2}$

myInstance1和myInstance2指向同一个c++对象。在

基本上是the same answer as that other question。在

相关问题 更多 >