Megaxela Megaxela - 1 year ago 71
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download