惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
IT之家
IT之家
V
Visual Studio Blog
The Cloudflare Blog
博客园 - 司徒正美
Jina AI
Jina AI
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
S
SegmentFault 最新的问题
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
T
Tailwind CSS Blog
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
爱范儿
爱范儿
博客园 - Franky
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - Lance Yang

批量插入Oracle,遇到CLob字段慢的解决办法 c#,利用WPF的ScaleTransform和TranslateTransform实现图片的缩放效果 自定义控件如何给特殊类型的属性添加默认值 z(转) Oracle 12c心得 Entity Framework Code First (八)迁移 Migrations EF Code First学习笔记 C#判断程序是由Windows服务启动还是用户启动 全方位掌握 NSIS 的操作 NSIS学习笔记(转) C#开源框架(整理) 十大前端开发框架(转) .Net 学习 C# 实现无焦点窗体(转载) C++C#时间转换 C#调用C++导出类(转) Socket异步发送的同步控制 自己编码实现数据库的映射实体的代码生成器 Digital image processing In C# C#数字图像处理(摘录)
C# P/Invoke中传递数组参数
Lance Yang · 2012-11-21 · via 博客园 - Lance Yang

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);
            }
        }

    }

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