Re: return pointer to a struct

Lenard Lindstrom <[email protected]> Thu, 28 May 2009 10:43:37 -0700
Newsgroups gmane.comp.python.pyrex
Message-ID <[email protected]>
horace wrote:
> hi,
>
> i have used ctypes so far but would like to try pyrex/cython for 
> better performance...
>
> i have a c library with a function which returns a pointer to a 
> struct. this struct should be exposed to python. it should be possible 
> to modify the variables of this struct from python and the c library 
> should see those changes.
>
> in ctypes this somehow works automagically but in pyrex/cython i can't 
> get this to work. is there a way to achieve this? can anyone point me 
> into the right direction?
> ------------------------------------------------------------------------
>
> _______________________________________________
> Pyrex mailing list
> [email protected]
> http://lists.copyleft.no/mailman/listinfo/pyrex
>   
Hi horace,

Pyrex doesn't automatically expose C structures to Python. It takes a 
bit of work first. Wrap the structure pointer in an extension type - 
cdef class - and add properties to the class for accessing the structure 
fields. To be Pythonic the C functions that create, destroy, and 
otherwise manipulate the C structure are called through methods of the 
extension type. The function that returns a pointer to a new structure 
would be called from the __cinit__ special method. A function that frees 
the structure would be called from __dealloc__. In this way access to a 
structure instance is controlled by the wrapping Python class. I have 
attached a simple, contrived example that involving a complex number 
structure. It builds with Cython, though with minor changes to setup.py 
it should also work with Pyrex.


Lenard Lindstrom
<[email protected]>

_______________________________________________
Pyrex mailing list
[email protected]
http://lists.copyleft.no/mailman/listinfo/pyrex
mycomplex.zip (application/zip, 1.5 KB) - not displayed