简体   繁体   中英

Serialize a structure in C# to C++ and vice versa

Is there an easy way to serialize a C# 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 C# 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

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);
        }
    }
}

Try Google Protocol Buffers . There are a bunch of .NET implementations of it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM