C++中的struct写成文件:
#include "stdafx.h"

struct TestStruct


...{

float f1;

float f2;

short s1;

short s2;

float arrf[8];

};


int _tmain(int argc, _TCHAR* argv[])


...{

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++)


...{

teststruct.arrf[i]=i;

}



if( fopen_s( &stream, "fread.out", "w+t" ) == 0 )


...{

fwrite( &teststruct, sizeof( teststruct ), 1, stream );

fclose( stream );

}

else

printf( "File could not be opened " );

return 0;

}


在C#中读取C++中生成的文件,并填充到C#中的结构中:
对应C++结构在C#声明如下:
读取文件到byte[]:
[StructLayout(LayoutKind.Sequential, Pack = 1)]

struct TestStruct


...{

float f1;

float f2;

short s1;

short s2;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]

float[] arrf;

}



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();


把byte[] 转换成TestStruct:
private static TestStruct GetTestStruct(byte[] b)


...{

IntPtr intprt =

GCHandle.Alloc(b, GCHandleType.Pinned).AddrOfPinnedObject();

int isize = Marshal.SizeOf(typeof(TestStruct));

TestStruct t =

(TestStruct)Marshal.PtrToStructure(intprt, typeof(TestStruct));

Marshal.FreeHGlobal(intprt);


return t;

}


