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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With