Byte arrays and DLLs

Edmondo Giovannozzi edmondo.giovannozzi at gmail.com
Fri Jul 1 05:01:04 EDT 2022


Il giorno venerdì 1 luglio 2022 alle 00:46:13 UTC+2 ery... at gmail.com ha scritto:
> On 6/30/22, Rob Cliffe via Python-list <pytho... at python.org> wrote: 
> > 
> > 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.
> You're overlooking the from_buffer() method. For example: 
> 
> >>> ba = bytearray(10) 
> >>> ca = (ctypes.c_char * len(ba)).from_buffer(ba) 
> >>> ca.value = b'spam&eggs' 
> >>> ba 
> bytearray(b'spam&eggs\x00') 
> 
> Note that the bytearray can't be resized while a view of the data is 
> exported. For example: 
> 
> >>> ba.append(97) 
> Traceback (most recent call last): 
> File "<stdin>", line 1, in <module> 
> BufferError: Existing exports of data: object cannot be re-sized 
> 
> >>> del ba[-1] 
> Traceback (most recent call last): 
> File "<stdin>", line 1, in <module> 
> BufferError: Existing exports of data: object cannot be re-sized

Have you had a look at numpy (https://numpy.org/)?
Typically, it is used for all scientific applications, supports several different kind of array, fast linear algebra, etc.
And of course you can pass an array to a dynamic library with ctypes (https://numpy.org/doc/stable/reference/routines.ctypeslib.html).

 


More information about the Python-list mailing list