[Pyrex] using C char array problem

Lenard Lindstrom len-l at telus.net
Tue May 23 20:10:52 UTC 2006


On 23 May 2006 at 11:44, Eric Colleu wrote:

> 
> Hi,
> 
> I have a problem with pyrex array management. 
> I define a type 
> ctypedef char machaine[10]
> And I try to pass an array of this type to a C function with no 
> success.
> Below is my C code and pyrex code.
> Please help me or I'm gonna be crazy...
> 
> Thanks
> 
[snip code]
> --- apienc.h --- Begin
> 
> typedef char machaine[10];
> 
> void testDeTableauDeString(machaine *montableau, int nbelt);

testDeTableauDeString takes an array of nbelt machaine.
> 
> --- apienc.h --- End
> --- pywrap.pyx --- Begin
> 
[snip code]
> def testapi(stringlist):
> cdef machaine *myarray

myarray is a pointer to a machaine.

> cdef machaine *p[10]

p is an array of ten pointers to machaine.

> cdef int buflen
> for i, s in enumerate(stringlist):
> print "Value of s : " + s
> PyObject_AsReadBuffer(s, <void **>&myarray, &buflen)
> p[i] = myarray
> print "buflen =", buflen
> print "Value of myarray : %s" % 
> PyString_FromStringAndSize(<char *>myarray, buflen)
> print "Value of p : %s" % 
> PyString_FromStringAndSize(<char *>p[i], buflen)
> testDeTableauDeString(p[0], len(stringlist))

testDeTableauDeString expects an array of len(stringlist) machaine 
but is instead getting the first machaine in the array of pointers p.

> 
> --- pywrap.pyx --- End

Do you want to work with an array of machaine or an array of pointers 
to machiane? Using PyObject_AsReadBuffer is a bad idea because if the 
python object is garbage collected the buffer pointer now points to 
invalid memory.

Lenard Lindstrom
<len-l at telus.net>




More information about the Pyrex mailing list