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;
} TEST;

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

This entry was posted on Monday, February 27th, 2006 at 02:50 and is filed under C++. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.