Converting Python code to C/C++

Kurt Smith kwmsmith at gmail.com
Tue Jun 23 11:49:53 EDT 2009


On Mon, Jun 22, 2009 at 9:49 PM, Andras
Pikler<Andras.Pikler at students.olin.edu> wrote:
> Hi!
>
>
>
> Short: I need to turn a Python program that I (mostly) wrote into C code,
> and I am at a loss.
>
>
>
> Long: I’m doing research/programming for a professor, and we are working
> with MIDI files (a type of simple music file). The research deals with
> generating variations from a musical melody; currently, my Python code uses
> a Python midi package I found online to read the notes in question from a
> midi file, about 350 lines of my own code to generate a variation based on
> these notes and the professor’s algorithms, and finally the package again to
> write the new melody to another midi file.
>
>
>
> Now, my professor would like to have this exact code in C/C++, as she
> believes C is more compatible with MATLAB, and wants the code to be
> available in multiple languages in case a programmer works for her in the
> future who knows C but not Python. While I know a tiny bit of C (emphasis on
> the tiny), I would much prefer if there were some sort of automatic compiler
> I could use to turn my Python code into C than taking a week or two or three
> to learn the minimum I need about C, find a way to access MIDI files in it,
> and rewrite all of my code.
>
>
>
> After some googling, I found and tried Shedskin, but it doesn’t work, as the
> Python midi package I’m using uses modules which Shedskin does not support.
> Otherwise, I haven’t found much. Is there anything out there to help me do
> this? If not, from anyone who has experience in this regard, how daunting
> should I expect this to be?


Taking on C from a cold start and being able to handle the ins and
outs of interfacing with Python isn't something that's feasible in
'two or three weeks'.  Here are a couple of options -- take 'em or
leave 'em:

1) Put the code in Cython: http://www.cython.org/  (full disclosure:
I'm doing a GSoC project with Cython).  It will convert pretty much
any python code into C code (even closures are supported in the most
recent version, I think), and the C code can then be compiled into an
extension module.

The only problem with the above is the C code isn't, at first blush,
easy to read.  Nor is it supposed to be changed by the user.  So that
leads us to option...

2) Write the core functionality in C yourself, and then wrap those C
functions in Cython.  You'll want to take a look at the documentation:

http://docs.cython.org/

and, more specifically on wrapping C code:

http://docs.cython.org/docs/external_C_code.html

I don't think you'll be able to avoid learning C, though.

Kurt



More information about the Python-list mailing list