Exposing a C++ API to Python

Question:

I’m currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.

The alternatives I tried were:

  • Boost.Python

    I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.

  • SWIG

    SWIG’s main advantage for us was that it doesn’t require end users to install it to use the final program.

What have you used to do this, and what has been your experience with it?

Asked By: Marcos Lara

||

Answers:

I’ve used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG’s. However, SWIG has much better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you’re more than half-way there to getting a Java/Perl/Ruby wrapper as well.

I don’t think there’s a clear-cut choice: for smaller projects, I’d go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.

Answered By: Max Maximus

pyrex or cython are also good and easy ways for mixing the two worlds.

Wrapping C++ using these tools is a bit trickier then wrapping C but it can be done. Here is the wiki page about it.

Answered By: Toni Ruža

I suggest SIP. SIP is better than SWIG due to the following reasons:

  1. For a given set of files, swig generates more duplicate (overhead) code than SIP. SIP manages to generate less duplicate (overhead) code by using a library file which can be statically or dynamically linked. In other words SIP has better scalability.

  2. Execution time of SIP is much less than that of SWIG. Refer Python Wrapper Tools: A Performance Study. Unfortunately link appears broken. I have a personal copy which can be shared on request.

Answered By: bhadra

EDIT – the Robin project is sadly abandoned, and won’t be much use today

I’ve used Robin with great success.

Great integration with C++ types, and creates a single .cpp file to compile and include in your shared object.

Answered By: orip

A big plus for Boost::Python is that it allows for tab completion in the ipython shell: You import a C++ class, exposed by Boost directly, or you subclass it, and from then on, it really behaves like a pure Python class.

The downside: It takes so long to install and use Boost that all the Tab-completion time-saving won’t ever amortize ;-(

So I prefer Swig: No bells and whistles, but works reliably after a short introductory example.

Answered By: wr.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.