C#泛型实现流中C/C++格式的struct数据的通用读取方法

背景简单提一下:好多个C/C++构成的结构体(struct)数据需要在C#中读取,他们可能在文件中或网络中(总之有办法转为流Stream)。
在C#中用Marshal的PtrToStructure()可以实现byte[]向struct的转变。
不过如果每个struct都要写个方法也太低效了,尤其是我现在遇到几十个struct的情况。。。。
研究了一下泛型(C#2.0就支持了),发现方法泛型可以解决这个问题。

实现了从流中读取struct的通用方法。代码如下:

  1. /// <summary>
  2. /// 从流中读取struct的通用方法
  3. /// </summary>
  4. /// <param name="_struct">struct类型</param>
  5. /// <param name="stream">流</param>
  6. /// <returns>字节读取数</returns>
  7. /// <see>http://bianbian.org/technology/333.html</see>
  8. public static int ReadStruct<T>(ref T _struct, Stream stream)
  9. {
  10.   int size = Marshal.SizeOf(_struct);
  11.   byte[] buffer = new byte[size];
  12.   size = stream.Read(buffer, 0, size); //已读取字节,用size少用一个变量
  13.   GCHandle pinned = GCHandle.Alloc(buffer, GCHandleType.Pinned);
  14.   _struct = (T)Marshal.PtrToStructure(pinned.AddrOfPinnedObject(), typeof(T));
  15.   pinned.Free();
  16.   return size;
  17. }

使用也很简单,实现了对struct数据的通用读取:

  1. Struct_bianbian_org tmp = new Struct_bianbian_org();
  2. .ReadStruct<Struct_bianbian_org>(ref tmp, stream);
  3. Struct2_bianbian_org tmp2 = new Struct2_bianbian_org();
  4. .ReadStruct<Struct2_bianbian_org>(ref tmp2, stream);

遗憾的是,从C/C++的struct转到C#的struct需要耗费比较多的人品。
我观察了一下,倒是可以考虑写个脚本自动切换。类似以前写的根据struct生成基于JSON-C的json_object代码

标签: , , ,

遵守创作共用协议,转载请链接形式注明来自 http://bianbian.org 做人要厚道
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值