使用 pybind11 包装C++分配的实例



当通过PyBind11在C++中嵌入python时,我遇到了以下问题。假设我通过C++生成一个对象的shared_ptr实例,然后我想将此指针移交给pybind11,以便为其生成"影子"python绑定。

这是我最初的非工作尝试:

#include <stdio.h>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
using namespace std;
namespace py = pybind11;
class Pet 
{
public:
Pet() {}
void bark(void) { printf("wow!n"); }
};
PYBIND11_PLUGIN(Pets) {
py::module m("Pets", "Say hello to our pets");
py::class_<Pet, shared_ptr<Pet>>(m, "Pet")
.def("bark", &Pet::bark)
;
return m.ptr();
}
int main(int argc, char *argv[])
{
py::scoped_interpreter guard{};
shared_ptr<Pet> pet = make_shared<Pet>();
// How do Ι "assign" Pet.pet to the C++ pet? This compiles,
// but throws a run time exception:
py::globals()["pet"] = py::cast(pet);
py::exec("pet.bark()n");
}

所以我的问题是:

  • 那么如何为C++ shared_ptr创建"影子类"呢?
  • 如何将C++ shared_ptr"赋值"给 python 变量?

如果你从强制转换中检查结果的py::object(例如,通过将其转换为布尔值(,你会看到调用失败。原因是蟒蛇不知道类"宠物"(也不知道shared_ptr(。您可以使用上面的代码并以通常的方式从中创建模块,然后将其导入主程序。或者,使用EMBEDDED_MODULE功能,该功能更接近您看起来想要的功能。

调整您的示例:

#include <stdio.h>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
using namespace std;
namespace py = pybind11;
class Pet
{
public:
Pet() {}
void bark(void) { printf("wow!n"); }
};
PYBIND11_EMBEDDED_MODULE(Pets, m) {
py::class_<Pet, shared_ptr<Pet>>(m, "Pet")
.def("bark", &Pet::bark)
;
}
int main(int argc, char *argv[])
{
py::scoped_interpreter guard{};
shared_ptr<Pet> pet = make_shared<Pet>();
auto pets_mod = py::module::import("Pets");
py::globals()["pet"] = py::cast(pet);
py::exec("pet.bark()n");
}

最新更新