我试图将python解释器嵌入到我的C++17应用程序中。我必须从python访问Foo的一个对象实例,它位于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;
}
}它在运行时崩溃: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())时,它做了我期望的事情(但显然不是我想要的)。
那我做错什么了?
发布于 2018-12-18 10:11:38
在嵌入式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(
// ....https://stackoverflow.com/questions/53830479
复制相似问题