[原] 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代码

©2012 便便代码人生. All Rights Reserved.

. 标签: C#, Marshal, struct, 泛型

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

posted @ 2009-03-02 21:27  便便嘘嘘  阅读(243)  评论(0编辑  收藏  举报