[Pyrex] How to use function defined in C-file?

Lenard Lindstrom len-l at telus.net
Wed Nov 9 20:56:16 CET 2005


First you need to declare the C function in an include file:

test00_h.h:
-----------------------------
void hello( int size );
-----------------------------

Next you need a 'cdef extern from' to use the include file in Pyrex:

cdef extern from "test00_h.h":
    void hello( int size )

Finally, C functions in a Pyrex module are not visible from Python. 
You need to wrap the C function call in a Python function. So finally 
you get:

test00.pyx
------------------------------
cdef extern from "test00_h.h":
    void c_hello "hello" ( int size )  # c_hello is alias for hello

def hello( int size ): # Python 'hello' function
    c_hello(size)        # C 'hello' function call
-------------------------------

Lenard Lindstrom
<len-l at telus.net>

On 9 Nov 2005 at 19:37, Tomasz Primke wrote:

> Hello.
> 
> I'm trying to make a module that uses a function defined in external C-file:
> 
> test00.pyx:
> ---------------------------
> cdef extern void hello( int size )
> ---------------------------
> 
> test00_c.c:
> ---------------------------
> #include <stdio.h>
> 
> void hello( int size )
> {
>  printf("Hello! %d\n", size);
> }
> ---------------------------
> 
> setup.py:
> ---------------------------
> import glob
> from distutils.core import setup
> from distutils.extension import Extension
> from Pyrex.Distutils import built_ext
> 
> TESTBASE = "build/temp.linux-i686-2.4"
> 
> setup(
> 	name = "Test",
> 	ext_modules = [
> 		Extension( "test00", ["test00.pyx", "test00_c.c"],
> 			   extra_objects = glob.glob( "%s/*" % TESTBASE )
> 			)
> 		],
> 	cmdclass = { 'build_ext': build_ext }
> 	)
> ---------------------------
> 
[snip]
> The only problem is that when I run Python and import this module, no 
> functions are available (there's no hello function):
> 
> >>> import test00
> >>> dir(test00)
> ['__builtins__', '__doc__', '__file__', '__name__']
> 




More information about the Pyrex mailing list