通过boost::python将C++对象传递给python函数
pass C++ object to python function by boost::python
我想在c++应用程序中使用嵌入式python,并调用python脚本中定义的函数。函数的参数是一个c++对象。查看我的代码:
class Test
{
public:
void f()
{
std::cout<<"sss"<<std::endl;
}
};
int main()
{
Py_Initialize();
boost::python::object main = boost::python::import("__main__");
boost::python::object global(main.attr("__dict__"));
boost::python::object result = boost::python::exec_file("E:\python2.py", global, global);
boost::python::object foo = global["foo"];
if(!foo.is_none())
{
boost::python::object pyo(boost::shared_ptr<Test>(new Test())); // compile error
foo(pyo);
}
return 0;
}
python2.py:
def foo(o):
o.f()
如何将c++对象传递给foo?我知道swig可以做到,但是boost::python?
已解决。
class Test
{
public:
void f()
{
std::cout<<"sss"<<std::endl;
}
};
//==========add this============
BOOST_PYTHON_MODULE(hello)
{
boost::python::class_<Test>("Test")
.def("f", &Test::f)
;
}
//===============================
int main()
{
Py_Initialize();
//==========add this============
inithello();
//===============================
boost::python::object main = boost::python::import("__main__");
boost::python::object global(main.attr("__dict__"));
boost::python::object result = boost::python::exec_file("E:\python2.py", global, global);
boost::python::object foo = global["foo"];
if(!foo.is_none())
{
boost::shared_ptr<Test> o(new Test);
foo(boost::python::ptr(o.get()));
}
return 0;
}
另一个主题
您需要将测试类型公开给Python,如下所示:http://wiki.python.org/moin/boost.python/HowTo
相关文章:
- 使用C++指针调用 python 函数
- 使用 pybind11 调用 Python 函数时避免复制输入数据
- 从 C++ 函数与 Python 函数返回的不一致值用于偏斜正态分布
- 如何使用 pybind11 将 python 函数保存到静态 c++ 容器中?
- 在 cpp 中嵌入 python:如何获取指向 python 函数(而不是 PyObject)的 C 指针?
- 困在PyObject_GetAttrString():如何从C++代码中获取Python函数脚本
- 如何通过C++在Python函数中传递字符串参数
- 在 C 代码中调用 Python 函数时第三次出现访问冲突写入位置错误
- 通过 Boost Python 将 Python 函数转换为 C++,用作回调
- 获取 C++ 中的 Python 函数参数名称
- 使用来自C++的任意数量的参数(在编译时未知)调用 Python 函数
- 如何从Qt C++项目运行Python函数
- 如何从 c++ 调用另一个文件中定义的 python 函数?
- 无法理解提升 python 函数导出中的语法
- 执行 c++ 中字符串中提供的 Python 函数
- 使用 pybind11 从 C++ 调用 Python 函数
- 从C 中的多个线程调用Python函数
- 使用 C++ 中的 python 函数
- 如何使用 pybind11 将 python 函数转换为 std::function
- TensorFlow:可用的Python函数的C++等价物