0

Here is an example of what I try to do:

import ctypes
MEM_SIZE = 1024*1024*128

# allocate memory (this is Windows specific)
ptr = ctypes.cdll.msvcrt.malloc(MEM_SIZE)

# make memory accessible to Python calls
mem = ctypes.string_at(ptr, MEM_SIZE)
# BAD: string_at duplicates memory

# store it to disk
open(r'test.raw', 'wb').write(mem)

In a nutshell: I have a plain memory pointer, I know the size of the block and want to store it on disk or reuse it as a numpy array.

How can I do that without generating a copy of the memory block?


Related question: stackoverflow: Fill python ctypes pointer (thanks to Brian Larsen for the hint)

1 Answer 1

2
ctypes_array = (ctypes.c_char * MEM_SIZE).from_address(ptr)
with open('test.raw', 'wb') as f:
    f.write(ctypes_array)

numpy_array = numpy.frombuffer(ctypes_array, dtype=numpy.byte)
numpy_array.tofile('test.raw')
Sign up to request clarification or add additional context in comments.

3 Comments

Great, your suggestion works w/o copying the data! Thanks a lot!
If you just want to store it and don't need the numpy array, you can do that with: open('test.raw', 'wb').write(ctypes_array)
@TomPohl OK, added that to my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.