How to read/write a struct to a System.IO.Stream

S

stephen fx

Hello all!

Using C/C++ I can do this:
struct MyStruct
{
int a;
char b;
};

MyStruct test;
fread(&test,sizeof(MyStruct),1,fp);

How can a do this in C#? I found a Stream class,maybe I can use
System::Read(byte[] buffer,int offset,int count)? I can get sizeof a struct,
but how to convert a struct object to byte[]??

thanks.
 
G

Greg Bacchus

You probably want to look at Serialization.

Mark the struct with the [Serializable()] attribute, then use the
BinaryFormatter or the SoapFormatter class to serialize/deserialize it
to/from the stream.

Greg
 
G

Greg Bacchus

If you're specifically talking about a bitmap or other picture, you should
use the existing System.Drawing.Bitmap class, but if you're just talking
about an arbitrary class from C++, you should use SOAP and the
SoapFormatter, that is what it is for. Soap is a special XML format for
describing objects, it is paintext readable, and therefore supposed to be
fairly easy to make from other programs.

If you mean something more complicated, you can make your class implement
the ISerializable interface (it still needs to have the [Serializable()]
attribute) and then you can write your own custom Serialize() and
Deserialize() methods.

I'm not sure, but I do believe that this may not be appropriate for writing
files with predetermined formats (such as a bitmap) as the serialised file
may contain overhead (that you can't control), which tells the deserialiser
the class type etc... but as I said, I'm not sure about that as I haven't
really looked. In which case, you'd probably just want to have Read(stream)
and Write(stream) methods in your class for doing that.

Hope this helps you :)
Greg


stephen fx said:
Yes,I think I should use Serialize.But how can I deal with the data
generated by other C/C++ program? For example,How can I write a .BMP file
reader in C#?

Than you for your help!


Greg Bacchus said:
You probably want to look at Serialization.

Mark the struct with the [Serializable()] attribute, then use the
BinaryFormatter or the SoapFormatter class to serialize/deserialize it
to/from the stream.

Greg

stephen fx said:
Hello all!

Using C/C++ I can do this:
struct MyStruct
{
int a;
char b;
};

MyStruct test;
fread(&test,sizeof(MyStruct),1,fp);

How can a do this in C#? I found a Stream class,maybe I can use
System::Read(byte[] buffer,int offset,int count)? I can get sizeof a struct,
but how to convert a struct object to byte[]??

thanks.
 

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