c# 两个intPtr之间内存拷贝

c#中的March 提供了intPtr数组与intPtr之间的转换,但intPtr之间的却没有,尝试过引入window的copymemory但是拷贝出来的是错的,经多次尝试发现借助byte[]是可以完成的。

下面直接上代码:

        public struct  SCENE
        {

              public uint dwSize;

            [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 40, ArraySubType = System.Runtime.InteropServices.UnmanagedType.I1)]
            public byte[] Name;
         }

      

       int tempSize=Marshal.SizeOf(typeof(SCENE));

        int tempTolSize= Marshal.SizeOf(typeof(uint))+tempSize*10;

       intPtr   pTotal=Marshal.AllocHGlobal(tempTolSize);

        //过程处理获得pTotal的数据

         //获取有效个数

           byte[] tempbyte = new byte[Marshal.SizeOf(typeof(uint))];
          Marshal.Copy(pstruWinWallParam, tempbyte, 0, Marshal.SizeOf(typeof(uint)));
          uint count = System.BitConverter.ToUInt32(tempbyte,0);     

       //获取详细信息

                   byte[] tempbyte1 = new byte[tempSize];
                    for (int i = 0; i < count; i++)
                    {
                        Marshal.Copy(pstruWinWallParam + uintSize + dwsize * i, tempbyte1, 0, dwsize);


                        SCENE scene = (SCENE)BytesToStruct(tempbyte1, typeof(SCENE));


                    }


//BytesToStruct方法

        public static object BytesToStruct(byte[] bytes, Type strcutType)
        {
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }



猜你喜欢

转载自blog.csdn.net/shu19880720/article/details/75035943