Megaxela Megaxela - 2 months ago 18
Python Question

C++ and Python tight integrating

I have C++ program and I want to add extension system with Python. But to achieve this I have to map Python object method calls to C++ method calls. Is this possible and if yes how to achieve.


Python part:

class Extension(AbstractExtension):
def __init__(self, cool_cpp_object):
self.o = cool_cpp_object

def some_method(self):

C++ part:

class SomeClass : public AnotherClass
void method_to_cpp();

I have to pass SomeClass instance to Extension instance method. Thankyou.


There are several ways of doing so (StoryTeller correctly notes Boost::Python, and there is Swig too). Personally, I find Cython's C++ integration exceptionally easy to use.

Create some header file, say classes.hpp, and in it put (along with guards, etc.):

class SomeClass : public AnotherClass
    void method_to_cpp();

Place the implementation in an implementation file the usual way.

Now create Cython file with an export of the interface you will use:

cdef extern from "classes.hpp":
cdef cppclass SomeClass:

and a Python wrapper:

cdef class PySomeClass:
     cdef SomeClass obj

     def method(self):

That's it, basically. You can import and use PySomeClass like a regular Python class.

The link above should explain how to build all the files.