[Cython] accessing ctype array's b_ptr

Ondrej Certik ondrej at certik.cz
Wed Jul 1 03:14:10 CEST 2009


On Tue, Jun 30, 2009 at 7:07 PM, Ondrej Certik<ondrej at certik.cz> wrote:
> On Tue, Jun 30, 2009 at 6:42 PM, Lisandro Dalcin<dalcinl at gmail.com> wrote:
>> On Tue, Jun 30, 2009 at 9:26 PM, Ondrej Certik<ondrej at certik.cz> wrote:
>>>
>>> However, this assumes some particular form of PyObject_HEAD. Once it
>>> changes, my code will segfault.
>>>
>>
>> Indeed. That changes when you use a debug build of Python (./configure
>> --with-pydebug).
>>
>>> So I guess the right way to do this is
>>> to write my own C header file with the above struct (e.g. using the
>>> PyObject_HEAD macro) and then just reference it using:
>>>
>>> cdef extern from "Python.h":
>>>    ctypedef void PyTypeObject
>>>
>>> cdef extern from "my_header.h":
>>>    ctypedef struct CDataObject:
>>>        char *b_ptr
>>>
>>> which should always work.
>>>
>>> What do you think?
>>>
>>
>> Provided that ctypes.h is not a public header, I would do exactly the
>> same as you...
>>
>> PS: Can you believe that ctypes, being intended to be a tool for easy
>> interoperation with C code, does not provide a public C API in order
>> to let third-party codes to take advantage?
>
> Indeed, it doesn't provide it on my Ubuntu. It sucks.
>
> One more question. I am using ctypes because using it I can take a
> list of floats and create a C array of it:
>
> (c_float * len(ptr))(*ptr)
>
> from historical reasons (I am adapting some opengl example from
> pyglet, that used that approach --- since pyglet uses ctypes to wrap
> opengl). I use cython, so I think a better way is to use numpy?
>
> opengl supports strides, but it's just one number, e.g. it has to be
> the same for all rows (as opposed to numpy). Is it safe to just copy

Ah, I think I am wrong. Numpy's strides is exactly what I need, right?

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html

so I just take *any*  numpy array, as long as it has the right dtype,
and then just pass the pointer to .data and strides to the opengl
function.

Very nice.

Ondrej


More information about the Cython-dev mailing list