Python ctypes align data structure

强颜欢笑 提交于 2019-12-04 07:42:20

The array is at most 31 bytes shy of alignment. To get an aligned array, over-allocate by 31 bytes and then, if the base address is misaligned, add an offset to make it aligned. Here's a generic function for this:

def aligned_array(alignment, dtype, n):
    mask = alignment - 1
    if alignment == 0 or alignment & mask != 0:
        raise ValueError('alignment is not a power of 2')
    size = n * ctypes.sizeof(dtype) + mask
    buf = (ctypes.c_char * size)()
    misalignment = ctypes.addressof(buf) & mask
    if misalignment:
        offset = alignment - misalignment        
    else:
        offset = 0
    return (dtype * n).from_buffer(buf, offset)

For example:

>>> arr = aligned_array(2**4, ctypes.c_double, 512)
>>> hex(ctypes.addressof(arr))
'0x1754410'
>>> arr = aligned_array(2**8, ctypes.c_double, 512)
>>> hex(ctypes.addressof(arr))
'0x1755500'
>>> arr = aligned_array(2**12, ctypes.c_double, 512)
>>> hex(ctypes.addressof(arr))
'0x1757000'
>>> arr = aligned_array(2**16, ctypes.c_double, 512)
>>> hex(ctypes.addressof(arr))
'0x1760000'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!