我试图创建一个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
的新实例,这不是我想要的。在
是的,我知道这个答案已经很晚了,但是之前提供的解决方案要么已经过时,要么以模糊的方式解决了问题。在
其他答案最大的问题是它们同时使用pybind和原始Python接口。使用pybind,您可以使用一个更简单、更好的解释器接口。在
遵循一个可以解决您的问题的实现。在
首先你会注意到我们使用了“embed.h”头文件。 这给了我们创建嵌入式模块的功能。在
再往下看,我们使用}。这是一个专门用于嵌入的宏。在
PYBIND11_EMBEDDED_MODULE
,而不是常规的PYBIND11_MODULE
或过时的{下一个有趣的部分是我们为结构定义的类型。除了
Dog
类型之外,我们还使用shared_ptr<Dog>
。这对于处理实例至关重要。当main
模块超出范围并开始清理时,它需要知道类/结构的类型是shared\ptr,否则会出现seg错误(原始指针在这里不可用,我个人认为这是一件好事)。在最后要指出的是,我们实际上使用
pybind11::scoped_interpreter
类作为解释器,而不是使用原始Python接口。在我找到了自己问题的答案。诀窍是以下两个概念的结合:
下面的方法说明了:
由于pybind11v2.2.0还有另一种方法,使用自定义构造函数包装:python init方法不再需要调用c++构造函数。您可以让它直接返回c++singleton实例。在
在您的案例中,声明可能看起来像:
在python中:
^{pr2}$myInstance1和myInstance2指向同一个c++对象。在
基本上是the same answer as that other question。在
相关问题 更多 >
编程相关推荐