C# P/Invoke中传递数组参数

C#在调用动态库接口,有时需要在C#中分配非托管内存,以便动态库可以写入返回的数据;有时我们需要传递一个复杂的数组等等。在C++的方法原型中,是一个*即指针,在C#的方法原型,相对应的可以是IntPtr,有些也可以直接使用[Out,In]等属性。

     对于基础数组的数组,可以使用

            Byte[] photoData = new Byte[CompressPhotoSize];
            GCHandle gh = GCHandle.Alloc(photoData, GCHandleType.Pinned);
            IntPtr AddrOfPhotoData = gh.AddrOfPinnedObject();

来获取到数组的开始指针。但对于具有非基元(非直接复制到本机结构中的)成员的实例不能被固定。即属性中有如字符串等属性的结构体,就不能被固化,会报ArgumentException异常。这时我们就要手动分配内存了。

           基本的成员方法有如下一些

 

    /// <summary>
    /// 非托管代码辅助工具。
    /// </summary>
    public class MarshalHelper
    {
        /// <summary>
        /// 把托管数组复制到内存块中。
        /// </summary>
        /// <typeparam name="T">结构的类型</typeparam>
        /// <param name="InputArray">要复制的数组</param>
        /// <returns></returns>
        public static IntPtr IntPtrFromStuctArray<T>(T[] InputArray) where T : new()
        {
            int size = InputArray.Length;
            T[] resArray = new T[size];
            //IntPtr[] InPointers = new IntPtr[size];
            int dim = IntPtr.Size * size;
            IntPtr rRoot = Marshal.AllocCoTaskMem(Marshal.SizeOf(InputArray[0]) * size);
            for (int i = 0; i < size; i++)
            {
                Marshal.StructureToPtr(InputArray[i], (IntPtr)(rRoot.ToInt32() +
                        i * Marshal.SizeOf(InputArray[i])), false);
            }
            return rRoot;
        }
        /// <summary>
        /// 从非托管的内存数据转换成托管数据。
        /// </summary>
        /// <typeparam name="T">结构的类型</typeparam>
        /// <param name="outArray">数据指针</param>
        /// <param name="size">数组的长度</param>
        /// <returns></returns>
        public static T[] StuctArrayFromIntPtr<T>(IntPtr outArray, int size) where T : new()
        {
            T[] resArray = new T[size];
            IntPtr current = outArray;
            for (int i = 0; i < size; i++)
            {
                resArray[i] = new T();
                Marshal.PtrToStructure(current, resArray[i]);
                Marshal.DestroyStructure(current, typeof(T));
                int structsize = Marshal.SizeOf(resArray[i]);
                current = (IntPtr)((long)current + structsize);
            }
            Marshal.FreeCoTaskMem(outArray);
            return resArray;
        }

        /// <summary>
        /// 将数据从托管对象封送到非托管内存块。使用完得释放指针。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="structure"></param>
        /// <returns></returns>
        public static IntPtr StructureToPtr<T>(T structure) where T : new()
        {
            IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(structure));

            Marshal.StructureToPtr(structure, buffer, false);
            return buffer;
        }

        /// <summary>
        /// 从指针中获取一个结构。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ptr"></param>
        /// <returns></returns>
        public static T PtrToStructure<T>(IntPtr ptr) where T : new()
        {
            T a = (T)Marshal.PtrToStructure(ptr, typeof(T));
            Marshal.FreeHGlobal(ptr);
            return a;
        }

        public static void FreeHGlobal(ref IntPtr ptr)
        {
            Marshal.FreeHGlobal(ptr);
        }

        /// <summary>
        /// 把一个结构转为一个Byte数组。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="structure"></param>
        /// <returns></returns>
        public static Byte[] StructToBytes<T>(T structure) where T : new()
        {
            Int32 size = Marshal.SizeOf(structure);
            IntPtr buffer = Marshal.AllocHGlobal(size);

            try
            {
                Marshal.StructureToPtr(structure, buffer, false);
                Byte[] bytes = new Byte[size];
                Marshal.Copy(buffer, bytes, 0, size);

                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }

        }

        //2、Byte[]转换为struct
        /// <summary>
        /// 把数组转为结构。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static T BytesToStruct<T>(Byte[] bytes) where T : new()
        {
            Int32 size = Marshal.SizeOf(typeof(T));
            IntPtr buffer = Marshal.AllocHGlobal(size);

            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return (T)Marshal.PtrToStructure(buffer, typeof(T));
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

    }

通过上方法获取到指针,传到动态库就行了,记得,操作完成后得显式删除该指针所分配的内存,以免产生泄露。

posted @ 2012-11-21 11:02  Lance Yang  阅读(2660)  评论(0编辑  收藏  举报