如何将一个非托管内存数组复制到同一非托管内存中?

4

我预留了10个128字节的存储空间。

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

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

我需要将src1src2的128字节元素复制到指定偏移量的dst中。 Marshal.Copy 不适用于此目的,因为srcdst位于非托管内存区域。
2个回答

5

Windows API函数memcopy可以解决问题。

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

此外,请看这个链接:

https://dev59.com/CXE85IYBdhLWcg3wr1oe#2658394

根据它的说法,您可以使用unsafe上下文手动传输必要的字节。


C# 中没有为此目的提供内置方法吗? - Mixer
如果你指的是Marshal类,那么不是。因为这个类是唯一的非托管工作器,所以还是不行。 - AgentFire
1
这不是Windows API函数! - Matthew Watson
你的原帖中有提到这是在 Mac 上吗?这是非常重要的信息!如果你担心可移植性,那么你在处理什么非托管代码呢? - Matthew Watson
@MatthewWatson 有些模块仅使用本地代码。 但它们是跨平台的。在我的代码中,我试图避免特定于平台的调用。 - Mixer
显示剩余2条评论

3
如果您想使用Windows API来完成此操作,请使用MoveMemory
[DllImport("Kernel32.dll", EntryPoint="RtlMoveMemory", SetLastError=false)]
static extern void MoveMemory(IntPtr dest, IntPtr src, int size);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接