【发布时间】:2019-05-18 17:17:31
【问题描述】:
我尝试将 python 解释器嵌入到我的 C++17 应用程序中。
我必须从 python 访问位于 C++ 世界中的 Foo 的对象实例。
所以我想出了以下代码:
#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
文档仅显示如何将int 和string 插入py::dict。
我猜 pybind11 知道 Foo,因为当我删除 (line of evil) 行并将代码替换为 from my_module import Foo; print(Foo().get()) 时,它会达到我的预期(但显然不是我想要的)。
那么,我做错了什么?
【问题讨论】: