用C#读取C/C++的struct数据类型生成的文件
C++中的struct写成文件:
#include "stdafx.h"
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
struct TestStruct
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
float f1;
float f2;
short s1;
short s2;
float arrf[8];
};
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
int _tmain(int argc, _TCHAR* argv[])
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
FILE *stream;
TestStruct teststruct;
teststruct.f1=1.0;
teststruct.f2=2.0;
teststruct.s1=3;
teststruct.s2=4;
for(int i=0;i<8;i++)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
teststruct.arrf[i]=i;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
if( fopen_s( &stream, "fread.out", "w+t" ) == 0 )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif)
{
fwrite( &teststruct, sizeof( teststruct ), 1, stream );
fclose( stream );
}
else
printf( "File could not be opened " );
return 0;
}
对应C++结构在C#声明如下:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TestStruct
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
float f1;
float f2;
short s1;
short s2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
float[] arrf;
}
读取文件到byte[]:
FileStream fs =
new FileStream("fread.out", FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] b = r.ReadBytes((int)fs.Length);
r.Close();
fs.Close();
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
把byte[] 转换成TestStruct:
private static TestStruct GetTestStruct(byte[] b)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
IntPtr intprt =
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
GCHandle.Alloc(b, GCHandleType.Pinned).AddrOfPinnedObject();
int isize = Marshal.SizeOf(typeof(TestStruct));
TestStruct t =
(TestStruct)Marshal.PtrToStructure(intprt, typeof(TestStruct));
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
Marshal.FreeHGlobal(intprt);
return t;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
posted on
2007-07-12 18:04
yuyk
阅读(
932)
评论()
编辑
收藏
举报