I recently found myself needing to call a C++ class from within Python. I didn’t want to call a separate process (as I had previously when using Thrift – see Using Apache Thrift for Python & C++); but rather to call a C++ library directly.
Before I go on I should say that there are a lot of different ways to do this is Python – and I’ve picked one that worked for me. Other techniques are available – and opinion seems quite divided as to which (if any) technique is ‘best’.
To start with we have our C++ class, written in the usual way.
Next we need to place a C wrapper around the C++ code – since the ctypes system cannot use C++ code… To do this we add the following to the bottom of the file.
Note that we need to provide a non-class-based name for each Method we want to call.
Or we could use CMake.
The following is the CMakeLists.txtto build foo.cpp.
Note that I was building on my Mac – hence the MacOS specific line 4. This will work okay on Linux; but it’s not needed.
Now that we’ve written and compiled our C++ – we now need to build a Python wrapper for the Class…
Note the requirement to define the argument types, and the type of the return value (even if there isn’t one – e.g. you’re returning void). Without this you’ll get a segmentation fault (etc.).
For example:
The full source code for this simple demo can be found here: