Hi,

I need to access ctype array's b_ptr. The array is defined in
Python-2.6.2/Modules/_ctypes/ctypes.h  as:

struct tagCDataObject {
    PyObject_HEAD
    char *b_ptr;        /* pointer to memory block */
    int  b_needsfree;   /* need _we_ free the memory? */
    CDataObject *b_base;    /* pointer to base object or NULL */
    Py_ssize_t b_size;  /* size of memory block in bytes */
    Py_ssize_t b_length;    /* number of references we need */
    Py_ssize_t b_index; /* index of this object into base's
                   b_object list */
    PyObject *b_objects;    /* dictionary of references we need to
keep, or Py_None */
    union value b_value;
};


So I wrote this cython code:

cdef extern from "Python.h":
    ctypedef void PyTypeObject

cdef struct CDataObject:
    Py_ssize_t ob_refcnt
    PyTypeObject *ob_type
    char *b_ptr

and then I use it like this:

    cdef object b = ptr
    cdef CDataObject *a = <CDataObject *>b
    cdef char *x = a.b_ptr
    c_glNormalPointer(type, stride, <GLvoid *> x)


where "ptr" is a normal python variable, which contains the ctype
array, I then extract the b_ptr and use it. It works.

However, this assumes some particular form of PyObject_HEAD. Once it
changes, my code will segfault. 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?

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

Reply via email to