RT很急,需要完整的C#代码Marshal的copy方法貌似只能复制一维数组另外最后要这个二维数组的内存地址多谢

解决方案 »

  1.   

    或者你直接调用API CopyMemory
    Marshal应该是可以的...不过我现在没有msdn....上班了再帮你看吧
      

  2.   

    大概是这样,看看是否在简化一下
    byte[] vBuffer = new byte[256];
    int[,] vInts = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
    IntPtr source = Marshal.UnsafeAddrOfPinnedArrayElement(vInts, 0);
    Marshal.Copy(source, vBuffer, 0, 6 * sizeof(int));
    for (int i = 0; i < 6 * sizeof(int); i++)
        Console.WriteLine(vBuffer[i]);
      

  3.   

    请问byte[] vBuffer =newbyte[256];
    6*sizeof(int)这两部分能给我解释下么?非常感谢
      

  4.   

    请问byte[] vBuffer = new byte[256];
    6 * sizeof(int)这两部分能给我解释下么?
    先把代码再优化一下
    int[,] vInts = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };byte[] vBuffer = new byte[vInts.Length * sizeof(int)];
    IntPtr source = Marshal.UnsafeAddrOfPinnedArrayElement(vInts, 0);
    Marshal.Copy(source, vBuffer, 0, vInts.Length * sizeof(int));
    for (int i = 0; i < vBuffer.Length; i++)
        Console.WriteLine(vBuffer[i]);首先我们得计算这个二维数组在内存中占用的空间(单位是byte)
    vInts.Length * sizeof(int) // 用元素个数乘上每个元素占用的空间其次我们要的到数组的内存起始地址(元素在内存中是顺序存放的)
    IntPtr source = Marshal.UnsafeAddrOfPinnedArrayElement(vInts, 0);
    目标地址也一样可以得到
    IntPtr dest = Marshal.UnsafeAddrOfPinnedArrayElement(vBuufer, 0);
    IntPtr类型即可和非托管内存转换了。