Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing a C++ API to Python

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?

like image 936
Marcos Lara Avatar asked Nov 10 '08 00:11

Marcos Lara


People also ask

Can Python integrate with C?

Any code that you write using any compiled language like C, C++, or Java can be integrated or imported into another Python script. This code is considered as an "extension." A Python extension module is nothing more than a normal C library.

What is C API in Python?

The Python/C API allows for compiled pieces of code to be called from Python programs or executed within the CPython interpreter. This process of producing compiled code for use by CPython is generally known as "extending" Python and the compiled pieces of code to be used are known as "extension modules".

Can Python communicate with C++?

You have two basic options: Run the C++ code and the python code as two separate programs, in two separate processes, and use a IPC mechanism. Link the C++ code against your code, as grc suggested.


2 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.

like image 190
Max Maximus Avatar answered Sep 28 '22 17:09

Max Maximus


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.

like image 25
orip Avatar answered Sep 28 '22 18:09

orip