[Pyrex] C-API implementation in Pyrex 0.9.6

Stefan Behnel stefan_ml at behnel.de
Thu Oct 11 20:19:28 CEST 2007


William Stein wrote:
> Can I ask a few naive questions about "the C-API support", since I know that
> me and _many_ of the people I work with are confused about what this support
> provides?  I'll just ask a few naive questions, and maybe your answers would
> be useful for me to add to the faq or documentation.

Sure. The main idea behind the C-API support for Pyrex/Cython is to automate this:

http://docs.python.org/ext/using-cobjects.html


> (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)
> 
> Definitely in Cython/Pyrex a few months ago the above wouldn't work.
> Is there a way to make it work now?

Yes. You can export the function from arith.pyx via the "api" keyword (in
Pyrex 0.9.6, Cython will follow here) and it will generate a file
"arith_api.h" and (if you want) a .pxd file that define it. Then the above
code should work.


>  And if so, what are the linking
> requirements (i.e. options to gcc or distutils)?

No linking required, pure runtime access.


> (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(...)
>    }
> 
> This is very natural to do because I might be mixing C and .pyx code,
> and this provides a way to reach back and get at Python data directly
> from C code.   Is there now a way to do this?

In exactly the same way, just with a little less automatism. The arith_api.h
files defines static function pointers for each exported function and a static
function that you can call to initialise the pointers based on the Python
module. So, #including the header file and calling that function is enough to
do the above.

To make my position regarding the Pyrex 0.9.6 implementation clear: I like the
Pyrex interface to this functionality, it is better and cleaner than my
original implementation, and Cython should follow here. I just dislike the
internal implementation that leaks too much into Python space, where it simply
does not belong at all.

Stefan




More information about the Pyrex mailing list