Boost.Python能将C++的结构体暴露给Python使用。可是在运用Boost.Python时,却遇到一个难题,
一、在C++定义一个新的结构体struct A
二、将此结构体暴露给Python解释器
三、现在在工程中生成结构体A的对象,A a。
四、但愿将a传入Python解释器进行运算,运算的函数写在某py文件中。
一直没有办法解决,但愿大虾帮助解答。 python
这个问题就是在c++中调用py实现的接口函数。
相似c++代码
struct a
{
int a ;
int b;
};
a temp;
GetPythonFunc( & temp ); //调用python函数,参数为必定结构体的引用.
这个结构体用boost能够导出给python. 可是这个参数要怎么传递给python代码呢? ios
最后在python mailist找到答案 c++
-------------------------------------------------- #include <boost/python.hpp> #include <iostream> using namespace boost::python; class World { public: void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; typedef boost::shared_ptr< World > world_ptr; BOOST_PYTHON_MODULE(hello) { class_<World>("World") .def("greet", &World::greet) .def("set", &World::set) ; register_ptr_to_python<world_ptr>(); } int main(int argc, char *argv[]) { Py_Initialize(); world_ptr worldObjectPtr (new World); worldObjectPtr->set("Hello from C++!"); try { inithello(); PyRun_SimpleString("import hello"); object module(handle<>(borrowed(PyImport_AddModule("__main__")))); object dictionary = module.attr("__dict__"); dictionary["pyWorldObjectPtr"] = worldObjectPtr; PyRun_SimpleString("pyWorldObjectPtr.set('Hello from Python!')"); } catch (error_already_set) { PyErr_Print(); } std::cout << "worldObjectPtr->greet(): " << worldObjectPtr->greet() << std::endl; Py_Finalize(); return 0; } -------------------------------------------------- Output: worldObjectPtr->greet(): Hello from Python!