[ctypes-users] cast function, other ideas
Brought to you by:
theller
From: Thomas H. <th...@py...> - 2004-10-12 20:19:41
|
I recently did some experiments wrapping parts of libxml2. I started with a pyrex module implemented by Martijn Faassen, and converted it to ctypes code. Mostly it was pretty straightforward, and the libxml header file has already been 'converted' to ctypes definitions by my brand new gccxml/parser/code generator combo (more on that later, in another post). One problem was that libxml represents string pointers by 'unsigned byte *', which in ctypes is spelled POINTER(c_ubyte). For string pointers, ctypes has the c_char_p type, and I didn't want to hack on the generated wrapper files, so I came up with a cast function. cast(ptr, c_char_p) returns a c_char_p instance, pointing to the same address as the ptr instance (an instance of POINTER(c_ubyte)). c_char_p has a .value attribute, which allows to access the nul terminated string pointed to. IMO, the cast() function is a better way to access the string at that address, instead of implementing .value attributes for all the POINTER(byte) types. Further, I think a get_string() function, which also takes a POINTER instance (or even an integer address) as parameter would be useful in ctypes, to make it easier to get these strings. With help of cast, it can be implemented in this way, although I would prefer to implement it in C to make it more efficient: def get_string(ptr): return cast(ptr, c_char_p).value While we're on it, other functions that would be useful may be these (iirc, Paul Moore had suggested something like this long time ago): memcpy, strcpy, wcscpy. All of these functions may be very useful, escpecially to use generated code, where there's no way to fix all the wrappers for exactly the argtypes and restype one really needs. Any thoughts? Thomas |