[Pyrex] char * python type with extensions

len-l at telus.net len-l at telus.net
Sat Jul 2 00:38:46 CEST 2005


On 1 Jul 2005 at 12:34, Nathaniel Haggard wrote:

> A C function returns data in a character array.  Python wrecks this by
> treating the data as a string.  To solve this I'm making an extension
> type that I can treat as a python object.
> 
> cdef class const_data:
> 	cdef char *tc
> 	
> 	cdef void setme(self, tree_cell *t):
> 		self.tc = t
> 
>        def dump(self):
>              ....
> 
> 
> I was hoping it could work like this:
> 
> char * tmp
> tmp = c_routine_that_returns_character_array()
> a = const_data()
> a.setme(tmp)
> dosomething(a)
> 
> But it's trying to coerce the char * to a pyhton string instead and
> that messes up the data.
> 
> Any ideas?
> 
I am guessing your C function does not return a NULL terminated string. But your 
example has too many black boxes to make a diagnosis. It just looks plain 
dangerous to me. What tmp is actually pointing too is a mystery so I cannot tell if it 
is safe to keep a pointer to it in a Python object. From what is visible the 
c_routine_that_returns_character_array return value does remain a character 
pointer until it enters dosomething.

Without more information I cannot make coding suggestions. Seeing the actual 
code, if it is not too large, would be the most help. Do you want the C function return 
value available to Python or just local to the Pyrex module? Do you want to use C 
functions or Python string methods on the data? The const_data class is probably 
unnecessary. Python strings can be built from binary data using 
PyString_FromStringAndSize.

Lenard Lindstrom
<len-l at telus.net>




More information about the Pyrex mailing list