首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pybind11 11::对象在pybind11 11::dict中

pybind11 11::对象在pybind11 11::dict中
EN

Stack Overflow用户
提问于 2018-12-18 09:57:36
回答 1查看 2.3K关注 0票数 2

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

所以我想出了以下代码:

代码语言:javascript
复制
#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())时,它做了我期望的事情(但显然不是我想要的)。

那我做错什么了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-18 10:11:38

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

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

代码语言:javascript
复制
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(

// ....
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53830479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档