c# - Marshal.Copy,将一个 IntPtr 数组复制到一个 IntPtr

标签 c# arrays copy marshalling intptr

我不知道 Copy(IntPtr[], Int32, IntPtr, Int32) 方法是如何工作的。 我虽然它可以将多个 IntPtr 中包含的数据复制到一个 IntPtr 中(如 MSDN 所述),但显然它没有像我预期的那样工作:

IntPtr[] ptrArray = new IntPtr[]
{
    Marshal.AllocHGlobal(1),
    Marshal.AllocHGlobal(2)
 };

 Marshal.WriteByte(ptrArray[0], 0, 0xC1);

 // Allocate the total size.
 IntPtr ptr = Marshal.AllocHGlobal(3);

 Marshal.Copy(ptrArray, 0, ptr, ptrArray.Length);

 // I expect to read 0xC1 but Value is always random!!
 byte value = Marshal.ReadByte(ptr, 0);

有人知道我是否将此方法用于并非其目的的事情吗?

最佳答案

    static void Main(string[] args)
    {
        IntPtr[] ptrArray = new IntPtr[]
        {
            Marshal.AllocHGlobal(1),
            Marshal.AllocHGlobal(2)
        };

        Marshal.WriteByte(ptrArray[0], 0, 100);

        int size = Marshal.SizeOf(typeof(IntPtr)) * ptrArray.Length;
        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.Copy(ptrArray, 0, ptr, ptrArray.Length);

        // Now we have native pointer ptr, which points to two pointers,
        // each of thme points to its own memory (size 1 and 2).

        // Let's read first IntPtr from ptr:
        IntPtr p = Marshal.ReadIntPtr(ptr);

        // Now let's read byte from p:
        byte b = Marshal.ReadByte(p);

        Console.WriteLine((int)b);    // prints 100

        // To do: release all IntPtr
    }

阅读评论中的解释。

关于c# - Marshal.Copy,将一个 IntPtr 数组复制到一个 IntPtr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167036/

相关文章:

c# - 通过字节数组转换发送图像,从 java 到 c#

c# - C# 函数参数中的方括号语法?

arrays - Sumologic - 将 JSON 数组拆分为多个记录

javascript - 为什么 Angular 会将索引 0 数组插入子数组而不是索引 1?

json - json。在Go中解码TCP连接并同时记录原始数据

c# - Vnext 参数 1 : cannot convert from 'string' to 'System.IO.Stream'

c# - WPF 最佳实践 : Do custom controls work well with the MVVM design?

Javascript - 如何连接两个不同大小的数组中的字符串值?

bash - 将具有特定名称的目录递归复制到维护结构的新位置

maven-2 - maven antrun 将资源复制到基础目标目录