I spent some time researching, I came up with a function that should allow me to allocate arbitrary aligned memory using ctypes, mainly relying on ctypes to store a reference to an unmanaged memory buffer, an instance starting in the aligned position in the buffer.
Still need to test this in production.
import ctypes def ctypes_alloc_aligned(size, alignment): bufSize = size+(alignment-1) raw_memory = bytearray(bufSize) ctypes_raw_type = (ctypes.c_char * bufSize) ctypes_raw_memory = ctypes_raw_type.from_buffer(raw_memory) raw_address = ctypes.addressof(ctypes_raw_memory) offset = raw_address % alignment offset_to_aligned = (alignment - offset) % alignment ctypes_aligned_type = (ctypes.c_char * (bufSize-offset_to_aligned)) ctypes_aligned_memory = ctypes_aligned_type.from_buffer(raw_memory, offset_to_aligned) return ctypes_aligned_memory
source share