分配内存以16字节对齐 [英] Allocate memory with 16 byte alignment

查看:257
本文介绍了分配内存以16字节对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Marshal.GlobalHAlloc 来分配内存。由于文件说:这种方法揭示从kernel32.dll中的Win32 LocalAlloc功能。 的GlobalAlloc 的文件说,这将是8字节对齐的,但 LocalAlloc 不要说关于对齐什么。结果
为例,我想分配1024个字节的16字节对齐。将它的工作原理时,我分配1024 + 16个字节,然后我检查指针%16?如果结果为0意味着内存对齐,当它不为0的,我只是递增指针,以适应我的期望。问题是我不知道,如果我对齐的指针是在物理内存中真正对齐?

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 wanna allocate 1024 bytes with 16 byte align. Will it works when I allocate 1024+16 bytes then I check pointer % 16? If result is 0 it mean 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆