Providing a Python wrapper to a C++ type.

Marco Nawijn nawijn at gmail.com
Tue Oct 16 07:46:17 EDT 2012


On Tuesday, October 16, 2012 1:39:44 PM UTC+2, Stefan Behnel wrote:
> Marco Nawijn, 16.10.2012 12:17:
> 
> > On Tuesday, October 16, 2012 10:11:52 AM UTC+2, aaron.l... at gmail.com wrote:
> 
> >> I have a C++ module where I have a defined, working type. How would I
> 
> >> make a wrapper for this type to be able to be used in Python? I am
> 
> >> familiar(-ish) with the C-API for functions but I can't see concretely how
> 
> >> one would include an interface to a type.
> 
> >>
> 
> >> Is it this? http://docs.python.org/release/2.7.3/extending/newtypes.html
> 
> > 
> 
> > There are a few ways of doing this. At least three come to my mind:
> 
> > 1. Wrap the C++ type yourself by using handcrafted code implemented with the Python C API
> 
> > 2. Use SWIG to wrap the C++ code and (semi) automatically create the wrapper (http://www.swig.org/)
> 
> > 3. Use BOOST Python to wrap the C++ code (http://www.boost.org/doc/libs/1_51_0/libs/python/doc/index.html)
> 
> > 
> 
> > I would highly discourage (1) unless you are very brave and curious. Ofcourse it is a nice excercise, but if you want something to work quickly I would recommend to use either (2) or (3).
> 
> > 
> 
> > I have used both SWIG and BOOST Python and either of them worked pretty well for me. In the end I selected BOOST Python, because I was only interested in the Python wrapping (SWIG could generate many other wrappers as well).
> 
> 
> 
> There's also Cython, which provides a very flexible way (unlike SWIG) of
> 
> doing these things easily (unlike C++ with Boost).
> 
> 
> 
> http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html
> 
> 
> 
> I agree with discouraging 1) in specific.
> 
> 
> 
> Stefan

Hi Stefan,

I never worked with Cython (but I know it is very powerful and interesting) but in my mind there are slight differences in usage scenario between e.g. Boost Python and Cython. For me the idea of Cython is that your main code is in Python, but you want to improve the performance of specific parts of the code. In that case, Cython is the way to go. In case of Boost Python, the scenario for me is that you have a main program/library in C++, but you want to be able use the functionality from Python. 

Do you agree with this view?

Marco



More information about the Python-list mailing list