Python code -> to C code

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Apr 29 08:41:02 EDT 2003


"Garrison Tsang" <hygt2 at cam.ac.uk> wrote in
news:b8lpof$q0f$1 at pegasus.csx.cam.ac.uk: 

> I know nothing about Python but know a fair bit about C.
> 
> There is a program written in Python by a friend.  It takes in a file
> and decrypts it , which I would like to integrate into a C program I
> am writing. I want to see how the python code was implemented and
> whether I can implement it is C.
> 
> Any solution for this?
> 

The easiest solution is to leave the program in Python and just call the 
relevant functions from C. Possibly the easiest way to do this would be to 
use Pyrex.

Here is a simple example of calling Python from C taken from the Pyrex 
distribution. The Pyrex code in the .pyx file can import and call any 
existing Python modules. You can also pass arguments and return results 
with automatic conversion from simple C types (more complex types you have 
to convert yourself).

---- main.c ----
#include "Python.h"
#include "embedded.h"

int main(int argc, char *argv) {
  Py_Initialize();
  initembedded();
  spam();
  Py_Finalize();
}
---- embedded.pyx ----
cdef public void spam():
  praise()

def praise():
  print "Spam, glorious spam!"
---- end ----

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list