如何分配16字节对齐的内存? [英] How to allocate memory with a 16 byte alignment?
问题描述
我使用Marshal.GlobalHAlloc
分配内存.如文档所述:此方法从Kernel32.dll中公开Win32 LocalAlloc函数.". GlobalAlloc
的文档说它将对齐8个字节,但是LocalAlloc
没有说任何关于align的内容.
I use Marshal.GlobalHAlloc
to allocate memory. As documentation says: "This method exposes the Win32 LocalAlloc function from Kernel32.dll.". GlobalAlloc
's documentation says it will be 8 byte aligned but LocalAlloc
don't say anything about align.
例如,我想分配1024个字节并确保它与16对齐.当我分配1024 + 16个字节然后检查指针%16时,它可以工作吗?如果结果为0,则表示内存已对齐;当结果不为0时,我只是增加指针以符合我的期望.问题是我不知道,如果我有对齐的指针,它真的在物理内存中对齐了吗?
For example I want to allocate 1024 bytes and ensure it is aligned by 16. Will it work when I allocate 1024+16 bytes then I check pointer % 16? If result is 0 it means memory is aligned, when it is not 0, I just increment pointer to fit my expectations. The problem is I don't know, if I have aligned pointer it is really aligned in physical memory?
推荐答案
所有Windows堆分配器按8对齐.您可以通过过度分配和调整指针来解决此问题,如下所示:
All Windows heap allocators align by 8. You can fix that by over-allocating and adjusting the pointer, like this:
var rawptr = Marshal.AllocHGlobal(size + 8);
var aligned = new IntPtr(16 * (((long)rawptr + 15) / 16));
// Use aligned
//...
Marshal.FreeHGlobal(rawptr);
这篇关于如何分配16字节对齐的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!