Conversion struct/class <--> array

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?
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
G

Guest

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.
 
D

Dean L. Howen

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top