C # binary file setup

Is there a way to configure the way a binary file is written to files so that I can read the file from a C ++ program?

For instance:

myBinaryWriter.Write(myInt); myBinaryWriter.Write(myBool); 

And in C ++:

 fread(&myInt, 1, sizeof(int), fileHandle); fread(&myBool, 1, sizeof(bool), fileHandle); 

EDIT: from what I see, if the length of the string is small enough to fit into one byte, while it writes it, which is bad if I want to read it in C ++.

+4
source share
2 answers

If you want to guarantee binary compatibility, perhaps the simplest approach from C # is to strip out the binary and just use the stream to write the bytes themselves. This way you get full control over the output.

Another approach would be to create an assembly that can write data using C ++ / cli, so you can get direct compatibility with C ++ from managed code.

+1
source

You have several options that you can choose:

  • Writing a byte separately. this is possibly the worst option. it requires more work on both sides (serialization and sides of serialization).
  • Use multiple platform serializers, such as Protobuf. it has ports for almost any platform, including C # (protobuf-net) and C ++. and it is also easy to use and has good performance.
  • you can use Struct and convert it to a byte array using Marshal.PtrToStructure (if you need another way, you can use Marshal.StructureToPtr). There are many examples on the Internet. If you can use Managed CPP, you can use the same object so that you can change the structure in one place, and it will change in both places.
  • If you are using Managed CPP, you can use built-in serializers like BinaryFormatter ...
0
source

All Articles