Allocating memory space from python3 and pass the pointer to C

Viewed 351

I have built a library consists of python layer and C++ layer. In the C++ layer I have a big chunk of memory that I need to keep in the heap so the chunk has to be allocated dynamically at the time of compilation.

What I want to do is to make this chunk of memory configurable from the python side. Is there a way to allocate memory space dynamically from python and pass the pointer to C++ layer ?

Thanks

2 Answers

You can use the ctypes library to make DLL/shared libraries calls.

Windows:

import ctypes
dwFlags = ctypes.c_int(0x00000008) # HEAP_ZERO_MEMORY
szSize = 256 # Size of the area you want to allocate

addr = ctypes.windll.kernel32.HeapAlloc(ctypes.windll.kernel32.GetProcessHeap(), ctypes.c_int(dwFlags), ctypes.c_int(szSize))

Now the variable addr holds the address of the memory allocated

Related