view raw
zgnilec zgnilec - 6 months ago 66
C# Question

How to allocate memory with a 16 byte alignment?

I use

to allocate memory. As documentation says: "This method exposes the Win32 LocalAlloc function from Kernel32.dll.".
's documentation says it will be 8 byte aligned but
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?


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