Pass C ++ object to python boost :: python function

I want to use the built-in python in the C ++ app and the call functions defined in the python script. A function parameter is a C ++ object. See my code:

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): of() 

How to pass a C ++ object to foo? I know swig can do this, but boost :: python?

+6
source share
2 answers

You need to expose your test type to Python, as shown here: http://wiki.python.org/moin/boost.python/HowTo

+2
source

solvable.

 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; } 

another topic

+2
source

Source: https://habr.com/ru/post/907215/


All Articles