[Pyrex] Wrapping c code

wrw3 at humboldt.edu wrw3 at humboldt.edu
Tue Aug 7 09:24:07 CEST 2007


While I've used pyrex to replace c code before I've never used it to wrap
existing c code. I decided to give it a try and realized that I have no
idea where to begin. So, assuming I have the following files:
##simple.h
int adder(int first, int second);

##simple_c.c
#include "simple.h"
int adder(int first, int second){
    return first + second;
}

how do I make adder available as a python function? I wrote the following
pyrex file:
##simple.pyx
cdef extern from "simple.h":
    int adder(int first, int second)

def add(first, second):
    return adder(first, second)

and this distutils script:
##setup.py
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
  name = "Simple",
  ext_modules=[Extension("Simple", ["simple.pyx"])],
  cmdclass = {'build_ext': build_ext}
)

but how do I tell pyrex about the contents of simple_c.c? Must I compile
simple_c.c as a shared library and use the libraries=[] keyword of
extension or is their a simpler method?




More information about the Pyrex mailing list