目标:将byte[]转成byte*以方便使用memcpy
[DllImport("kernel32.dll", EntryPoint = "RtlCopyMemory", CharSet = CharSet.Ansi)]
public extern static long CopyMemory(IntPtr dest, IntPtr source, int size);
private void butTemp_Click(object sender, EventArgs e)
{
unsafe
{
byte[] by1 = new byte[4] { 1, 2, 3,4 };
IntPtr tempMemoryPointer = Marshal.AllocHGlobal(4);
fixed (byte* converted = by1)
{
CopyMemory(tempMemoryPointer, new IntPtr(converted), 4);
}
byte* p1 = (byte*)tempMemoryPointer.ToPointer();
//此时p[0]到p[3]分别为: 1 2 3 4
}
}
扩展目标:取int的地址以使用memcpy
private void butTemp_Click(object sender, EventArgs e)
{
unsafe
{
int iTmp = 0x11223344;
IntPtr tempMemoryPointer = Marshal.AllocHGlobal(4);
int* converted = &iTmp;
CopyMemory(tempMemoryPointer, new IntPtr(converted), 4);
byte* p1 = (byte*)tempMemoryPointer.ToPointer();
//此时p[0]到p[3]分别为: 0x44 0x33 0x22 0x11
}
}
测试环境
win7 + VS2022