On May 22, 2009, at 4:21 PM, Ryan Dingman wrote:

> How can I store a reference to a Python object in a C struct? If I try
> to define a C struct as follows:
>
> ctypedef struct my_struct:
>    object my_object
>
> Cython tells me "C struct/union member cannot be a Python object". So,
> I thought I'd try storing the objects as void *
>
> ctypedef struct my_struct:
>    void *my_object
>
> But this is obviously problematic because when I make an assignment:
>
> my_struct.my_object = <void *>some_object
>
> The proper ref counting won't occur. Is there a way that I can
> manually ref count this object? Is there another approach for storing
> Python objects in a struct?
>
> Any help would be appreciated.

The reason it is disallowed is because Cython is unable to do the ref- 
counting automatically. Your approach of casting to/from a void* is  
the right one to do here (but the duty is on you to be careful about  
it).

To do things manually, import the relevant functions as

from python_ref cimport Py_DECREF, Py_INCREF

See http://hg.cython.org/cython/file/c6388e2a9739/Cython/Includes/ 
python_ref.pxd

- Robert

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to