[Tutor] pass a memory pointer to a c function
Eryk Sun
eryksun at gmail.com
Sun Jan 30 00:15:37 EST 2022
On 1/29/22, Nathan Smith <nathan-tech at hotmail.com> wrote:
>
> I actually managed to figure this out myself, but do have a related
> question (I hope you all don't mind!).
>
> My solution was:
>
> import ctypes
> data=b/"some text"
> x=bytearray(data)
> Buffer = ctypes.c_char * len(x)
> buf = Buffer.from_buffer(x)
> addr=ctypes.addressof(buf)
>
> My question is, do I need to free that buffer? Will python do it when
> the object is deleted?
buf is a buffer export of the bytearray. While `buf` is referenced,
the bytearray remains allocated and cannot be resized.
That said, the following is the typical way to create a mutable buffer
from bytes data:
buf = ctypes.create_string_buffer(data)
This creates a ctypes.c_char array that's null terminated. All of the
data is copied to the array, even if it contains null bytes.
As a function argument, a C array is passed as a pointer to the first
element, so you shouldn't need ctypes.addressof() in most cases.
More information about the Tutor
mailing list