How to allocate memory with a 16 byte alignment?

对着背影说爱祢 提交于 2019-12-21 12:41:40

问题


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.

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?


回答1:


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);


来源:https://stackoverflow.com/questions/13413323/how-to-allocate-memory-with-a-16-byte-alignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!