8 July 2010
Python can be extended or embedded. The only option discussed here is writing extensions.
For extending python you need to write an extension module by hand or generate one automatically. Those are some of the main available options:
- ctypes: Ctypes is a python module that load *.dll and *.so libraries dynamically and make the functions inside the library available from python. It is cross-platform. Types conversion is made at runtime making it slower but development time is much faster.
- Write extension by hand: If there are many functions in the library it can be a hard task. Exceptions and types need to be converted explicitly.
- swig: It parses the header file *.h and generate *.cxx c++ code that is a extension for python. Also, a python module is generated as a interface between python and the c++ library. To parse the header files can be very difficult and sometimes it is necessary to write "interface files".
- boost::python: is a package from Boost that makes it easier to write C++ extension for python. It includes functions for common tasks like type and exception conversions.
- pyste: is a generator for boost::python. It produces boost::python code automatically but it doesn't try to parse the *.h header files, which is a hard tasks, but instead relays on gcc to parse it and generate XML code that it ultimately use.
- PyCXX: is another generator.
If it needs to be cross platform probably the best option is ctypes.
It seems that the better option if C++ code is being developed from scratch is to use pyste because at the C++ side the boost classes are available to interface with the python objects from C. But using pyste means that when source code is distributed the end user needs to have gcc installed. With swig you distribute the C++ *.cxx generated code
The advantage of Swig is that code to interface with several languages can be generated, not only to python. *.so files need to be stripped the symbol table to greatly reduce their size. This can't be done automatically from distutils.
References:
- ctypes A foreign function library for Python - Python documentation](). Using ctypes to call dynamic libraries.
- Extending Python with C or C++ - Python documentation
- Wrapping a C library in Python. Discussion on swig, pyste, boost::python and ctypes.
Related tags: c, python