用PybDn11包包装C++分配实例

2024-05-16 02:03:34 发布

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

在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");
}

所以我的问题是:

    那么我如何为C++ SyrdypTR创建一个“影子类”呢?你知道吗如何将C++的SypDypTR分配给Python变量?你知道吗

Tags: topyincludenamespaceclassintsharedpybind11
1条回答
网友
1楼 · 发布于 2024-05-16 02:03:34

如果从cast检查结果py::对象(例如,通过将其强制转换为bool),您将看到调用失败。原因是python不知道类“Pet”(也不知道共享的ptr)。您可以像上面那样使用代码,用通常的方法从中创建一个模块,然后将其导入主程序。或者,使用嵌入的模块功能,它更接近您想要的。你知道吗

调整示例:

#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");
}

相关问题 更多 >