利用Boost::Python实现C++调用python接口
11月06日
阅读数:7
这篇文章主要向大家介绍利用Boost::Python实现C++调用python接口,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。
Boost.Python能将C++的结构体暴露给Python使用。可是在运用Boost.Python时,却遇到一个难题,
一、在C++定义一个新的结构体structA
二、将此结构体暴露给Python解释器
三、现在在工程中生成结构体A的对象,Aa。
四、但愿将a传入Python解释器进行运算,运算的函数写在某py文件中。
一直没有办法解决,但愿大虾帮助解答。 python
这个问题就是在c++中调用py实现的接口函数。
相似c++代码
structa
{
inta;
intb;
};
atemp;
GetPythonFunc(&temp);//调用python函数,参数为必定结构体的引用.
这个结构体用boost能够导出给python.可是这个参数要怎么传递给python代码呢? ios
最后在pythonmailist找到答案 c++
--------------------------------------------------
#include
#include
usingnamespaceboost::python;
classWorld
{
public:
voidset(std::stringmsg){this->msg=msg;}
std::stringgreet(){returnmsg;}
std::stringmsg;
};
typedefboost::shared_ptrworld_ptr;
BOOST_PYTHON_MODULE(hello)
{
class_("World")
.def("greet",&World::greet)
.def("set",&World::set)
;
register_ptr_to_python();
}
intmain(intargc,char*argv[])
{
Py_Initialize();
world_ptrworldObjectPtr(newWorld);
worldObjectPtr->set("HellofromC++!");
try{
inithello();
PyRun_SimpleString("importhello");
objectmodule(handle<>(borrowed(PyImport_AddModule("__main__"))));
objectdictionary=module.attr("__dict__");
dictionary["pyWorldObjectPtr"]=worldObjectPtr;
PyRun_SimpleString("pyWorldObjectPtr.set('HellofromPython!')");
}catch(error_already_set){
PyErr_Print();
}
std::cout<greet():"<greet()<<
std::endl;
Py_Finalize();
return0;
}
--------------------------------------------------
Output:
worldObjectPtr->greet():HellofromPython!