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!