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

推荐订阅源

Simon Willison's Weblog
Simon Willison's Weblog
G
Google Developers Blog
Spread Privacy
Spread Privacy
I
InfoQ
V
V2EX
S
Schneier on Security
小众软件
小众软件
C
CERT Recently Published Vulnerability Notes
博客园 - 聂微东
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
L
Lohrmann on Cybersecurity
Recent Announcements
Recent Announcements
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Attack and Defense Labs
Attack and Defense Labs
云风的 BLOG
云风的 BLOG
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
C
Cybersecurity and Infrastructure Security Agency CISA
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
Latest news
Latest news
S
Secure Thoughts
Project Zero
Project Zero
MongoDB | Blog
MongoDB | Blog
I
Intezer
Security Latest
Security Latest
Apple Machine Learning Research
Apple Machine Learning Research
Vercel News
Vercel News
N
Netflix TechBlog - Medium
V2EX - 技术
V2EX - 技术
量子位
T
Threatpost
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
T
Tor Project blog
A
Arctic Wolf
Microsoft Security Blog
Microsoft Security Blog
T
The Exploit Database - CXSecurity.com
大猫的无限游戏
大猫的无限游戏
T
Tailwind CSS Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Check Point Blog
博客园 - Franky
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
The GitHub Blog
The GitHub Blog
L
LINUX DO - 热门话题

博客园 - 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);
            }
        }

    }

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