tags:

views:

177

answers:

4

hi i am writing a project in C# i wanna save a class in binary file and then read that file it in C i wanna know how can i do it without serialize and deserialize please help me

+4  A: 

Saving the state of an object to a file means serializing it.

Reading the state of an object from a file means deserializing it.

You have to use serialization/deserialization to do what you want.

Since you need to do this across different languages, using the built in serializers would probably not be very helpful.

You can use one of the XML serializers for the C# part, but then would have to parse the XML out in c.

Another option is to write your own custom serizlizer to do this. This way you have full control over the file format.

Oded
+7  A: 

You are talking about cross-platform serialization.

A few options:

  • serialize it as text (xml, json); text is still binary, after all - and simple
  • serialize it manually
  • use a third party cross-platform serializer

But whatever you do, don't use BinaryFormatter. The reason I stress this is that it is probably the first thing you'll see if you search for C# binary serialization, but is entirely inappropriate for your purposes. The format is proprietary, and includes type information that only makes sense from .NET (not really from unmanaged C).

I'm quite attached to "protocol buffers" as a serialization API, and there are both C# and C versions here.

Marc Gravell
"text is still binary, after all" -> Good statement. Is there anything in a computer which isn't binary then? :)
codymanix
@codymnix lot's of stuff but no data :p
Rune FS
A: 

I presume you mean you want to have a C# application write a file. Then have a separate C/C++ application read that file? On that assumption, in C# you'll need to look into the System.IO namespace, and specifically the FileStream class.

On a side note, I'd really recommend writing a C# Class Library project that handles this read/write via .NET serialization classes and then invoke it nativly from your C# code, and use COM ([assembly: ComVisible(true)]) to access your .NET code from your C/C++ code.

Nate Bross
@Nate: P/Invoke is a one-way street; while you can use it to call native methods from within .NET, you cannot use it to call .NET methods from within native code. Your only options for invoking managed code from within unmanaged code is hosting the .NET runtime. Given that, I would discourage this approach.
Adam Robinson
You're right, what I meant was to make the .NET class `[assembly: ComVisible(true)]`.
Nate Bross
A: 

Do you want to save a class? This is not possible since classes are compiled into assemblies (exe,dll) in .net.

I think what you want is to save the state of an object or better suited, a struct to a file.

You can write all fields of the class to a file using the BinaryWriter class. Also you can have a look at this.

codymanix