首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Marshal.Copy,将IntPtr数组复制到IntPtr中

Marshal.Copy,将IntPtr数组复制到IntPtr中
EN

Stack Overflow用户
提问于 2014-11-27 17:23:42
回答 1查看 10.3K关注 0票数 6

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

代码语言:javascript
复制
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);

有没有人知道我是否在使用这个方法做一些不是它的目的的事情?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-27 18:08:12

代码语言:javascript
复制
    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
    }

阅读评论中的解释。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27167036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档