Can python-C++ extension get a C++ object and call its member function? -
i writing python/c++ application, call methods in c++ extension python.
say c++ has class:
class { private: int _i; public: a(int i){_i=i;} int get_i(){return _i;} } a=a(); it there anyway python can a object in c++ , call member function, i.e.:
import cpp_extension a=cpp_extension.a() print a.get_i() any reference general reading appreciated.
yes. can create python c++ extension c++ objects visible within python if built-in types.
there 2 main ways go it.
1.create extension following documentation provided in cpython api documentation.
2.create extension using tool such boost::python or swig.
in experience boost::python best way go (it saves enormous amount of time, , price pay depend on boost).
for example, boost::python bindings follows:
// foo.cpp #include <boost/python.hpp> class { public: a(int i) : m_i{i} { } int get_i() const { return m_i; } private: // don't use names such `_i`; reserved // implementation int m_i; }; boost_python_module(foo) { using namespace boost::python; class_<a>("a", init<int>()) .def("get_i", &a::get_i, "this docstring a::get_i") ; } compile:
g++ -o foo.so foo.cpp -std=c++11 -fpic -shared \ -wall -wextra `python2.7-config --includes --libs` \ -lboost_python and run in python:
>>> import foo >>> = foo.a(2) >>> a.get_i() 2 >>> print a.get_i.__doc__ get_i( (a)arg1) -> int : docstring a::get_i c++ signature : int get_i(a {lvalue})
Comments
Post a Comment