[Pyrex] C-API implementation in Pyrex 0.9.6

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Oct 12 01:58:29 CEST 2007


William Stein wrote:
> (1) Suppose I would like to define a cdef'd function in a module
> arith.pyx that I want
> to call from other .pyx files, e.g.,
> 
> cdef int fast_gcd(int a, int b):
>    ...
> 
> Then I basically want to do this sort of thing from other .pyx files:
>     from arith cimport fast_gcd
>     int x = fast_gcd(5,7)

Yes. You can do that by declaring fast_gcd in a .pxd file, e.g.

   # arith.pxd
   cdef int fast_gcd(int, int)

   # arith.pyx
   cdef int fast_gcd(int a, int b):
     ...

   # anothermodule.pyx
   from arith cimport fast_gcd
   x = fast_gcd(5,7)

That's all you need to do. No linking is required.

> (2) Suppose I want to define a cdef'd function in a .pyx file, as above, but now
> I want it to be callable from some external C file.  E.g.,
> 
> /* this is a C function in a .c file */
>    int foo(blah) {
>        fast_gcd(...)
>    }

1) Declare the function as "api" in the .pyx file:

   # arith.pyx
   cdef api int fast_gcd(int a, int b):
     ...

2) Include the generated header in your C code and call the
    importing function:

   /* somefile.c */
   #include "arith_api.h"
   ...
      int x
      import_arith()
      x = fast_gcd(p, q)

In this case, the object file produced by compiling arith.pyx
needs to be linked against the object file produced by compiling
somefile.c, either statically or dynamically.

--
Greg



More information about the Pyrex mailing list