pybind11::object in pybind11::dict
pybind11::object in pybind11::dict
我尝试将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
文档仅显示如何将int
和string
插入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(
// ....
相关文章:
- Pybind11:将元组列表从Python传递到C++
- Windows/Cygwin - 不能使用 pybind11 - 犯错误
- 用pybind11包装C++抽象类时出错
- 使用Pybind11向Python公开Eigen::张量
- 如何在C++中使用pybind11加载一个pickle python列表
- 使用JsonCpp将数据返回到带有pybind11的python会在python调用中产生Symbol not foun
- 如何将 Eigen::Ref 与 pybind11 一起使用?
- 相当于 pybind11 中的 boost::p ython py::scope().attr()
- Python 3.8 不能与 Pybind11 一起导入 [Windows]
- 如何通过 pybind11 从 python 中的C++中捕获异常?
- Pybind11 错误未定义对"Py_GetVersion"的引用
- Pybind11 Class Definition
- 在Raspbian上编译pybind11测试用例时出现致命错误
- 特征返回类型的 pybind11 问题
- 将 pybind11 绑定标记为已弃用的最佳方法
- pybind11 运行测试用例
- 使用 pybind11 共享 MPI 通信器
- 使用 pybind11 包装 yaml-cpp 迭代器
- 如何构建一个 setup.py 来编译C++使用 Python、pybind11 和 Mingw-w64 的扩展?
- pybind11::object in pybind11::dict