• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++带有指针数组的结构体转换为C#可用的结构体

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 带有指针数组的结构体不能直接转换为C#类型的结构体,转换起来有点麻烦

 

先定义出对应C++类型的C#结构体
       public struct user_group_t
       {
           public int id;
           public string name;
       }


       public struct user_group_list
       {
           public int group_array_count;

           public IntPtr group_array;//指向 user_group_t类型的指针
       }

 

泛型函数实现转换功能

public static List<T> MarshalPtrToStructArray<T>(IntPtr p, int count)
        {
            List<T> l = new List<T>();
            for (int i = 0; i < count; i++, p = new IntPtr(p.ToInt32() + Marshal.SizeOf(typeof(T))))
            {
                T t = (T)Marshal.PtrToStructure(p, typeof(T));
                l.Add(t);
            }
            return l;
        }

 

调用方式

通常C++函数返回一个指向user_group_list类型的指针,在C#中可使用IntPtr ptrGroupList对应指针,

而user_group_list类型结构体内包含的内容是长度为 group_array_count,地址为 group_array 的数组

因为IntPtr不能如C++的指针一样进行 ptrGroupList++这样的操作,所以要访问其内部成员需要把它转换为数组或list

   使用Marshal.PtrToStructure把指向结构体的指针转换为具体的结构体

    user_group_list   tructList = (user_group_list)Marshal.PtrToStructure(ptrStructGroupList, typeof(user_group_list));

    再使用泛型转换函数实现转换

    List<user_group_t> listGroupTemp = MarshalPtrToStructArray<user_group_t>(structList.group_array, structList.group_array_count);

   

     对于list的成员访问,就方便多了

     欢迎大家提出更多更方便的转换方式

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# 递归与非递归算法与数学公式发布时间:2022-07-10
下一篇:
如何在C#中实现窗体全屏模式发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap