Megaxela Megaxela - 12 days ago 6
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.

Example:

Python part:

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

def some_method(self):
self.o.method_to_cpp()


C++ part:

class SomeClass : public AnotherClass
{
public:
void method_to_cpp();
}


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

Answer

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
{
public:
    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:
    method_to_cpp()

and a Python wrapper:

cdef class PySomeClass:
     cdef SomeClass obj

     def method(self):
         self.obj.method_to_cpp()

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.

Comments