How to copy a array of unmanaged memory into the same unmanaged memory

耗尽温柔 提交于 2020-01-14 13:47:06

问题


I reserved memory 10 items of 128 bytes

IntPtr dst = Marshal.AllocHGlobal (10 * 128);

IntPtr src1 = Marshal.AllocHGlobal (128);
// .... init scr1 from DLL
IntPtr src2 = Marshal.AllocHGlobal (128);
// .... init scr2 from DLL

I need to copy the 128 bytes elements of src1 and src2 to dst at the specified offset.

Marshal.Copy not suitable for such purposes. Since the src and dst in unmanaged memory area.


回答1:


The Window's API function memcopy should do the trick.

[DllImport("msvcrt.dll", EntryPoint = "memcpy",
    CallingConvention = CallingConvention.Cdecl, 
    SetLastError = false)]
public static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count);

Also, check this out:

https://stackoverflow.com/a/2658394/558018

As it claims, you can use unsafe context to manually transfer necessary bytes.




回答2:


If you want to use the Windows API to do this, use MoveMemory.

[DllImport("Kernel32.dll", EntryPoint="RtlMoveMemory", SetLastError=false)]
static extern void MoveMemory(IntPtr dest, IntPtr src, int size);


来源:https://stackoverflow.com/questions/15610236/how-to-copy-a-array-of-unmanaged-memory-into-the-same-unmanaged-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!