Byte arrays and DLLs
Rob Cliffe
rob.cliffe at btinternet.com
Thu Jun 30 17:36:09 EDT 2022
I have an application in which I wanted a fixed-length "array of bytes"
(that's intended as an informal term) where I could read and write
individual bytes and slices, and also pass the array to a DLL (one I
wrote in C) which expects an "unsigned char *" parameter.
I am using ctypes to talk to the DLL but am open to alternatives. Speed
is important. My OS is Windows 10.
I started off using a bytearray object (bytes does not support item
assignment), but I couldn't find any way of passing it to the DLL
directly. Instead I had to convert it to a different type before
passing it, e.g.
bytes(MyArray)
or
(ctypes.c_char * LEN).from_buffer(MyArray)) # LEN is the length of
MyArray, knownin advance
but this was slow, I think because the array data is being copied to a
separate object.
Eventually after consulting Googol I came up with using a memoryview:
MyArray = memoryview(bytearray( <required-length> )) # can read
and write to this
and passing it to the DLL as
MyArray.tobytes()
and was gratified to see a modest speed improvement. (I don't know for
sure if it is still copying the array data, though I would guess not.)
Is this a sensible approach, or am I still missing something?
AKAIK it is not possible to give ctypes a bytearray object and persuade
it to give you a pointer to the actual array data, suitable for passing
to a DLL. Is this (a) false (b) for historical reasons (c) for some
other good reason?
TIA
Rob Cliffe
More information about the Python-list
mailing list