Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you set <code>tx.restype = POINTER(c_ubyte)</code>, the resulting ctypes pointer object is a buffer of either 4 or 8 bytes for the <em>address</em> of the image buffer. You need to create a ctypes array from this address. </p> <p>If you know the size ahead of time, you can set <code>SIZE = WIDTH * HEIGHT * 4; tx.restype = POINTER(c_ubyte * SIZE)</code>. Otherwise set <code>tx.restype = POINTER(c_ubyte)</code>, and cast to the dynamic size, i.e. <code>size = w * h * 4; pbuf = cast(result, POINTER(c_ubyte * size))</code>. Either way, you need to dereference the pointer to get at the array. Use either <code>buf = pbuf[0]</code> or <code>buf = pbuf.contents</code>. Then you can pass <code>buf</code> to <code>Image.frombuffer</code>.</p> <p>That said, it's usually simpler to allocate memory using ctypes. This gives you reference-counted memory management instead of having to manually free memory. The following is a toy example. </p> <p>Assuming a dynamic size, the caller needs to get the image dimensions in order to allocate the array, so I've added a struct that has the width, height, and depth of the image, which gets filled in by the C function <code>get_image_info</code>. The function <code>get_image</code> receives a pointer to the image array to copy in data. </p> <pre><code>import ctypes lib = ctypes.CDLL('imgtest.dll') class ImageInfo(ctypes.Structure): _fields_ = ( ('width', ctypes.c_int), ('height', ctypes.c_int), ('depth', ctypes.c_int), ) pImageInfo = ctypes.POINTER(ImageInfo) pImage = ctypes.POINTER(ctypes.c_ubyte) lib.get_image_info.argtypes = [pImageInfo] lib.get_image_info.restype = ctypes.c_int lib.get_image.argtypes = [pImage] lib.get_image.restype = ctypes.c_int imgnfo = ImageInfo() lib.get_image_info(ctypes.byref(imgnfo)) w, h, d = imgnfo.width, imgnfo.height, imgnfo.depth imgdata = (w * h * d * ctypes.c_ubyte)() lib.get_image(imgdata) from PIL import Image img = Image.frombuffer('RGBA', (w, h), imgdata, 'raw', 'RGBA', 0, 1) </code></pre> <p>C declarations:</p> <pre><code>typedef struct _ImageInfo { int width; int height; int depth; } ImageInfo, *pImageInfo; typedef unsigned char *pImage; int get_image_info(pImageInfo imgnfo); int get_image(pImage img); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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