您的位置:首页 > 编程语言 > C#

c# 两个intPtr之间内存拷贝

2017-07-12 17:31 253 查看
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);

            }

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息