首页 新闻 会员 周边

参数为结构变量

0
悬赏园豆:5 [已解决问题] 解决于 2011-11-21 16:02
public static TestStruct FromBinaryReaderBlock(BinaryReader br)
{    //Read byte array    byte[] buff = br.ReadBytes(Marshal.SizeOf(typeof(TestStruct)));   
 //Make sure that the Garbage Collector doesn't move our buffer    
 GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned);   
 //Marshal the bytes    TestStruct s =       (TestStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),      typeof(TestStruct));   
 handle.Free();//Give control of the buffer back to the GC    
 return s;
}

想用这段程序,但结构是直接指定的,如果结构是个变量应该怎么写?
问题补充:

就像这个样子的

/// byte数组转结构
public object RawDeserialize(byte[] bytes, Type anytype)
{


int size = Marshal.SizeOf(anytype); //得到结构的大小


if (size > bytes.Length)//byte数组长度小于结构的大小
{

return null;//返回空
}

IntPtr structPtr = Marshal.AllocHGlobal(size);//分配结构大小的内存空间

Marshal.Copy(bytes, 0, structPtr, size); //将byte数组拷到分配好的内存空间

object obj = Marshal.PtrToStructure(structPtr, anytype);//将内存空间转换为目标结构

Marshal.FreeHGlobal(structPtr); //释放内存空间

return obj;//返回结构
}

freewzx2005的主页 freewzx2005 | 初学一级 | 园豆:8
提问于:2011-11-01 09:09
< >
分享
最佳答案
0

什么意思,没看懂,你的意思是想:TestStruct ts=FromBinaryReaderBlock(br);想这么用?

收获园豆:5
顾晓北 | 专家六级 |园豆:10844 | 2011-11-01 09:56

对不同的二进制文件要定义不同的结构STRUCT, 我不可能每读一个文件都写这样一个函数,所以想把结构弄成一个变量再调用.

freewzx2005 | 园豆:8 (初学一级) | 2011-11-01 12:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册