在C和C++中有像_aligned_malloc
这样的函数,但我找不到任何用于对.NET对象在内存中进行对齐的方法。
在C和C++中有像_aligned_malloc
这样的函数,但我找不到任何用于对.NET对象在内存中进行对齐的方法。
更正 -- 您需要创建一个P/Invocable DLL,然后调用它来执行aligned_malloc函数。以下是示例C++代码:
#include <malloc.h>
extern "C" {
__declspec(dllexport) void* alMlc(size_t size, size_t alginment) {
return _aligned_malloc(size,alginment);
}
}
C# 代码(假设您创建的DLL名为mallocer.dll):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication7
{
class Program
{
[DllImport("mallocer.dll", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr alMlc(int size, int alignment);
static void Main(string[] args)
{
unsafe
{
//分配64字节的非托管内存,精确对齐到64字节
char* str = (char*)alMlc(64,64).ToPointer();
str[0] = 'H';
str[1] = 'i';
str[2] = '!';
str[3] = '\0';
Console.WriteLine(System.Runtime.InteropServices.Marshal.PtrToStringAuto(new IntPtr(str)));
}
Console.ReadKey();
}
}
}