Note that there are some explanatory texts on larger screens.

plurals
  1. POPython and C interop: Dynamic resizing of ctypes
    text
    copied!<p>I'm trying to interop with C in Python, and I have the following function prototype:</p> <pre><code>int testout(unsigned char *test, int *size) </code></pre> <p>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. </p> <p>From the <a href="http://docs.python.org/library/ctypes.html#variable-sized-data-types" rel="nofollow">Python ctypes manual</a>:</p> <p>"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:</p> <pre><code>&gt;&gt;&gt; short_array[:] [0, 0, 0, 0] &gt;&gt;&gt; short_array[7] Traceback (most recent call last): ... IndexError: invalid index &gt;&gt;&gt; </code></pre> <p>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."</p> <p>Great! I'm getting IndexError:invalid index, just as the example shows. And they decided not to show how to do this properly! :)</p> <p>Does anyone know how to resize a ctype properly? </p> <p>Here is my example code that works, except for the resizing:</p> <pre><code>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]) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload