I’m trying to interop with C in Python, and I have the following function prototype:
int testout(unsigned char *test, int *size)
The size of the unsigned char is determined by the size parameter. So I need a way to resize the buffer in Python dynamically to adjust to the size returned from the function call. This has been very difficult for me to figure out.
From the Python ctypes manual:
“This is nice and fine, but how would one access the additional elements contained in this array? Since the type still only knows about 4 elements, we get errors accessing other elements:
>>> short_array[:]
[0, 0, 0, 0]
>>> short_array[7]
Traceback (most recent call last):
...
IndexError: invalid index
>>>
Another way to use variable-sized data types with ctypes is to use the dynamic nature of Python, and (re-)define the data type after the required size is already known, on a case by case basis.”
Great! I’m getting IndexError:invalid index, just as the example shows. And they decided not to show how to do this properly! 🙂
Does anyone know how to resize a ctype properly?
Here is my example code that works, except for the resizing:
from ctypes import *
lib = "test.so"
dll = cdll.LoadLibrary(lib)
print "Testing pointer output"
dll.testout.argtypes = [POINTER(c_ubyte), POINTER(c_int)]
sizeout = c_int(0)
mem = (c_ubyte * 20)()
dll.testout(mem, byref(sizeout))
print "Sizeout = " + str(sizeout.value)
for i in range(0,sizeout.value):
print "Item " + str(i) + " = " + str(mem[i])
Here’s an example of what we were discussing. This code expects the caller to allocate the buffer.
Test code (Windows)
Python
Output