[Pyrex] Wrapping c code

Stefan Behnel stefan_ml at behnel.de
Tue Aug 7 09:31:36 CEST 2007



wrw3 at humboldt.edu wrote:
> 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?

Assuming simple_c.c is a straight C source file that should be part of your
module, you can just add it to the list of Extension source files (right next
to simple.pyx). That way, Pyrex will compile simple.pyx into a C source file
and distutils will compile both C files and link them into a single extension
module.

Stefan




More information about the Pyrex mailing list