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

限于喜欢 提交于 2019-12-24 08:39:38

问题


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


回答1:


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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/1229728/serialize-a-structure-in-c-sharp-to-c-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!