Hi, Is there an easy way to serialize a csharp structure and then deserialize it from c++. I know that we can serialize csharp structure to xml data, but I would have to implement xml deserializer in c++. what kind of serializer in csharp would be the easiest one to deserialize from c++? I wanted two applications (one C++ and another csharp ) to be able to communicate using structures of data
+2
A:
Try Google Protocol Buffers. There are a bunch of .NET implementations of it.
Mehrdad Afshari
2009-08-04 20:24:08
+1
A:
Boost has serialization libraries that allow XML , Binary and Text serialization. I'd say it's a pretty easy scenario where you serialize to XML in C++ using Boost, and deserialize in C#.
If you wish to have 2 applications communicating with each other, I'd also recommend considering networking. C# has built in sockets, C++ has Boost::Asio , it's pretty easy to communicate over 127.0.0.1 :)
Hope that helps
Maciek
2009-08-04 22:38:04
A:
Here's a class I wrote to convert a .NET structure to an array of byte, which allows to pass it easily to a C/C++ library :
public static class BinaryStructConverter
{
public static T FromByteArray<T>(byte[] bytes) where T : struct
{
IntPtr ptr = IntPtr.Zero;
try
{
int size = Marshal.SizeOf(typeof(T));
ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, ptr, size);
object obj = Marshal.PtrToStructure(ptr, typeof(T));
return (T)obj;
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
}
public static byte[] ToByteArray<T>(T obj) where T : struct
{
IntPtr ptr = IntPtr.Zero;
try
{
int size = Marshal.SizeOf(typeof(T));
ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, true);
byte[] bytes = new byte[size];
Marshal.Copy(ptr, bytes, 0, size);
return bytes;
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
}
}
Thomas Levesque
2009-08-04 22:52:01