Conversion struct/class <--> array

  • Thread starter Thread starter Dean L. Howen
  • Start date Start date
D

Dean L. Howen

Hi friends,
In C++, we can declare a struct and write it into file just by giving the
address the strct instance (using &).
for example:
/////////////////////////////////

typedef struct Test
{
int intV;
char charV[8];
float floatV;
};

// create a struct
Test ts;
ts.intV = 100;
strcpy(ts.charV, "12345678");
ts.floatV = 99.99;

CFile f;
....
f.Write(&ts, sizeof(TEST)); <-->
....

////////////////////////////

My question is:
in C#, could we read/write a struct/class from/to file?

how to convert a class/struct to an array?
 
Dean,

Unfortunately, there isn't a really easy way to do this. If you wanted,
you could call the CreateFile API through the P/Invoke layer and get the
handle to the file, and then call a version of ReadFile which has a managed
signature to take the structure into it (which it would populate on the way
back from interop).

Other than that, there really isn't a good way to do it except by
reading the bytes, and then populating the structure yourself.

Hope this helps.
 
you can use a binaryformatter to do binary serialization to and from a byte
stream, but the resulting stream isn't very interop friendly because it
contains more than just the data. type information is also saved for
deserialiation I believe.
 
Thanks so much for your replies

I think. I must define a method that Convert to byte array. After that,
passing this array to BinaryWriter. But it not a good way because of many
steps.
 
Back
Top