在C++中通过pyByD11嵌入Python时,我遇到了以下问题。考虑我通过C++生成对象的SyrdYPPTR实例,然后我想把这个指针切换到pybDun11,以生成一个“影子”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");
}
所以我的问题是:
如果从cast检查结果py::对象(例如,通过将其强制转换为bool),您将看到调用失败。原因是python不知道类“Pet”(也不知道共享的ptr)。您可以像上面那样使用代码,用通常的方法从中创建一个模块,然后将其导入主程序。或者,使用嵌入的模块功能,它更接近您想要的。你知道吗
调整示例:
相关问题 更多 >
编程相关推荐