pybind11::object in pybind11::dict

pybind11::object in pybind11::dict

本文关键字:pybind11 dict object in      更新时间:2023-10-16

我尝试将python解释器嵌入我的C 17应用程序中。我必须访问Foo的对象实例,该实例居住在C 中,来自Python。

所以我想出了以下代码:

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

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

文档仅显示如何将intstring插入py::dict

我猜Pybind11知道Foo,因为当我删除该行(line of evil)并用from my_module import Foo; print(Foo().get())替换代码时,它可以执行我的期望(但显然不是我打算的)。

那么,我在做什么错?

在嵌入式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(
// ....