在python ctypes中控制内存对齐 [英] control memory alignment in python ctypes
问题描述
我正在研究使用ctypes来处理C函数,这些函数处理必须在16个字节边界上对齐的SSE(__m128)数据。
I'm looking into using ctypes for using C functions manipulating SSE (__m128) data that have to be aligned on 16 bytes boundaries.
我找不到一个控制ctypes分配的内存对齐方式的简单方法,因此,现在,我正在使ctypes调用C函数,该函数提供正确对齐的内存缓冲区。
I could not find a simple way to control the alignment of memory allocated by ctypes, so, right now, I'm making ctypes call a C function that provides a correctly aligned memory buffer.
这种方法的问题在于,我必须手动显式释放该内存以防止其泄漏。
The problem I have with this approach is that I have to manually explicitly release this memory to prevent it from being leaked.
有没有办法控制由ctypes分配的内存的对齐方式?或者有没有方法注册清除函数来释放由ctypes调用的C函数分配的内存(标准python运算符 __ del __ 除外)?
Is there a way to control the alignment of memory allocated by ctypes ? or is there a way to register a cleanup function to release memory allocated by a C function called by ctypes (apart from standard python operator __del__) ?
遵循的最佳路径是什么?
What is the best path to follow ?
推荐答案
我一直在学习一些在研究的时候,我想出了一个函数,该函数应允许我为ctypes分配任意对齐的内存,基本上是基于ctypes应该在未对齐的内存缓冲区上保留引用,同时使实例在内存中的对齐位置开始的事实。
I've been taking some time to investigate, I came up with a function that should allow me to allocate arbitrary aligned memory with ctypes, basically relying on the fact that ctypes should keep a reference on the unaligned memory buffer, while having an instance starting at an aligned position in the buffer.
仍然必须在生产环境中对此进行测试。
Still have 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
这篇关于在python ctypes中控制内存对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!