pybind11::dict 中的 pybind11:: 对象

pas*_*sbi 2 c++ python pybind11

我尝试将 python 解释器嵌入到我的 C++17 应用程序中。Foo我必须从 python 访问位于 C++ 世界中的的对象实例。

所以我想出了以下代码:

#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
#include <iostream>

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

class Foo
{
public:
  Foo() : v(42) {}
  int get() const { return v; }
  void set(int x) { v = x; }
private:
  int v;
};

PYBIND11_EMBEDDED_MODULE(my_module, m) {
    py::class_<Foo>(m, "Foo")
      .def(py::init<>())
      .def("get", &Foo::get)
      .def("set", &Foo::set);
}

int main()
{
  py::scoped_interpreter guard{};
  using namespace py::literals;

  py::object py_foo = py::cast(Foo());
  auto locals = py::dict(
    "foo"_a = py_foo            // (line of evil)
  );

  // CRASH!
  try {
    py::exec("print(foo.get())", py::globals(), locals);
    return EXIT_SUCCESS;
  } catch (const std::exception& e) {
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
  }
}
Run Code Online (Sandbox Code Playgroud)

在运行时崩溃:Unable to convert call argument 'foo' of type 'object' to Python object

该文档仅显示如何将int和插入stringpy::dict.

我猜 pybind11 知道Foo,因为当我删除该行(line of evil)并将代码替换为时from my_module import Foo; print(Foo().get()),它会执行我所期望的操作(但显然不是我想要的)。

那么,我做错了什么?

lll*_*lll 5

在嵌入式Python解释器中,需要先导入模块,否则Python不知道该模块存在。

添加py::module::import("my_module");到您的main()

int main()
{
  py::scoped_interpreter guard{};

  py::module::import("my_module");  // <-- Here, import the module
  using namespace py::literals;

  py::object py_foo = py::cast(Foo());
  auto locals = py::dict(

// ....
Run Code Online (Sandbox Code Playgroud)