Skip to content
Advertisement

How do I copy a part of bytearray to c_void_p-referenced memory and vice versa?

In the Python application, I have a bytearray with some data. My python code is called by some external native library (DLL/so/dylib) (using ctypes and its callback functions). One of the callback functions includes a pointer to the unmanaged buffer, allocated in that external library.

I need to copy a part of the bytearray into this unmanaged buffer or copy contents of the unmanaged buffer into the bytearray at specific location.

To put it simply, I have

JavaScript

In other languages, the answer would be simple – I’d either call the dedicated method (e.g. in .NET Framework’s Marshal class), or get the pointer to the specific byte in the bytearray (in native languages like C++ or Pascal) and be done. Unfortunately, I don’t see how to do either of these operations in Python without an intermediate bytes() or similar buffer.

I have some methods which use the intermediate bytes() instance, but copying the data just because there’s no way to get a pointer seems to be weird to me.

I am looking for version-independent solution, if possible, but can live with python3-only one as well. Thank you in advance.

Advertisement

Answer

Listing [Python.Docs]: ctypes – A foreign function library for Python.

What you’re looking for is possible. Arrays (CTypes) come in handy.
Below it’s a “small” example. For demo purposes, the buffers only contain “human friendly” chars.

dll00.c:

JavaScript

code00.py:

JavaScript

Output:

JavaScript

Needless to say that going outside (C) buffer’s bounds, would yield Undefined Behavior (and my code doesn’t perform that kind of checks).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement