tags:

views:

153

answers:

2

I'm working on converting an old C program (currently run on UNIX) into our C# system.

The program builds some data into several structs and then writes a file using a series of fwrites like this:

fwrite ( &loc,  sizeof ( struct loc_items ),  1, hdata.fp );

With loc being the data, struct loc_items being the struct it's a type of.

My question is if I will be able to match this file output with C#? Assuming I can match the endian format and sizes of floats, ints, etc.

Since it's writing the entire struct in the fwrite, I don't know the order that it's writing the different variables of the struct. Also is there any issue with padding around the struct the fwrite might put?

Any advice?

+3  A: 

Make a quick unit test that generates a file using the ported C# version and then does a compare of the contents from a file generated by the system. Then you will at least have a test that discovers discrepancies automatically.

Peter Lillevold
+5  A: 

You have a variety of options.

  • Use BinaryWriter and write each field of the struct individually.
  • Use marshalling to get an array of bytes for the struct and write that to your stream.
  • Use a library like Miguel de Icaza's struct library.

Personally, I dislike the use of marshalling in this context. I would simply add some "Open/Save", "Read/Write", "Hydrate/Dehydrate", "Serialize/Deserialize" methods to your struct or class.

class POCO {
    int aaa;
    double bbb;

    public void Read(BinaryReader r) {
        aaa = r.ReadInt32();
        bbb = r.ReadDouble();
    }
    public void Write(BinaryWriter w) {
        w.Write(aaa);
        w.Write(bbb);
    }
}

This way, you're in full control of what gets read and written.

Frank Krueger
+1, BinaryWriter will also be faster than using marshalling.
0xA3
is there an endian issue with this? For aaa, is the high byte or the low byte written first? What about for the double? More importantly, is that something to really worry about?
Ankur Goel
**No**, there is no endianness issue. Given that he used to be writing the struct directly from memory to disk, he obviously wasn't concerned about little vs big and was depending upon his machines architecture.
Frank Krueger
@divo, I wonder if you have any references for that. I'm very curious about the performance of serialization so would love to see any studies done.
Frank Krueger