[Tutor] Moving my C++ code to Python?

Stefan Behnel stefan_ml at behnel.de
Sat Oct 16 10:34:54 CEST 2010


Paul, 15.10.2010 23:29:
> I have a software written in C/C++ but considering porting most of it
> to python, as it seems like it's a better choice for decision making
> portion of the code.

Write a wrapper first.


> I'm also thinking about having a 'matlab' like
> interface for reading, processing, and writing.

Sure, why not. For example, the Sage math system has an interactive console 
and a web app (the Sage notebook) for that purpose.


> In my current C++ code, I would read data into a vector of structs
> (which contains other simple vectors, strings, and structs) and it can
> be as large as 500MB to 2GB.  The data gets processed (requires random
> access).  The result is then written out.
>
> I would like to make modules for python.  The problem is that the
> vector of structs that is very large.  First, is it possible to pass
> such structures around to and from python and C/C++?

Easily. Your best bet is to keep the working code in C++ and write a 
wrapper in Cython. That will make it easy to write the plain wrapper code, 
and to give it a pythonic look-and-feel where you want it. It's certainly a 
lot more fun than digging your way through SWIG and also a lot more powerful.

http://cython.org/


> What would be
> the overhead cost of having a large structure that needs to be passed
> to and from the C/C++ modules?

Pretty low, but depends on the level of granularity. Calling from Python to 
C++ for each element may kill you, but a higher level interface will 
usually work very well and is easy to write in Cython.

Stefan



More information about the Tutor mailing list