4

Is there a way to customize the way a binary writer writes out to files so that I could read the file from a C++ program?

Eg:

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 can see, if the length of a string is small enough to fit into one byte then that's how it writes it, which is bad if I want to read it back in in C++.

Tom Tetlaw
  • 83
  • 1
  • 10
  • 21
  • 2
    possible duplicate of [serialize in .NET, deserialize in C++](http://stackoverflow.com/questions/2364077/serialize-in-net-deserialize-in-c) – Eric J. Jul 14 '12 at 16:05

2 Answers2

1

If you want to guarantee binary compatibility, possibly the easiest approach from c# is to ditch binary writer and just use a stream to write the bytes yourself. That way you get full control of the output data

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

Jason Williams
  • 56,972
  • 11
  • 108
  • 137
0

You have some options you can choose:

  • Writing it byte-byte by yourself. this is possibly the worst option. it requires more work in both sides (the serializing and the de-serializing sides).
  • Use some cross-platforms serializers like Protobuf. it has ports for almost any platform, including C# (protobuf-net) and C++. and it's also easy to use and has really good performance.
  • you can use Struct and convert it yo byte array using Marshal.PtrToStructure (if you need the other way, you can use Marshal.StructureToPtr). there are plenty of examples in the internet. If you can use Managed CPP, you can use the same object so you can change the struct in one place and it will change in both places.
  • if you use Managed CPP, you can use the built-in serializers, such as BinaryFormatter...
Shahar Gvirtz
  • 2,418
  • 1
  • 14
  • 17