Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

27 Feb 2006

Reading unmanaged structs with .NET

Last week i’ve spend a lot of time studying System::Runtime::InteropServices. It took me a while to figure out how i could read unmanaged structs with .NET System::IO. Here is a bit of sample code (Should be obvious enough to write a template or generic class for all sorts of structs, just like i did at the office)

typedef struct {
char name[9];
int name;
double sterr;

FileStream ^f = gcnew FileStream("C:\\TEST.DAT", FileMode::Open, FileAccess::ReadWrite);
BinaryReader ^r = gcnew BinaryReader(f);
array<byte> ^buf = r->ReadBytes(sizeof(TEST));
TEST test;
Marshal::Copy(buf, 0, (IntPtr) &test, sizeof(TEST));