msgpack可以在C#中打包用户定义的对象,将包发送到C ++应用程序然后解压缩吗?

我有一个C#reply服务器,可以打包一个对象并将其发送给请求者C#客户端。 我可以做同样的事情,但是C#reply服务器与C ++请求者客户端进行通信吗?

这是我的C#回复服务器的一个例子:

using System; using System.Text; using ZMQ; using MsgPack; namespace zmqMpRep { public class Weather { public int zipcode; public int temperature; public int humidity; } public class zmqMpRep { public static void Main(string[] args) { Socket replier = new Socket( SocketType.REP ); replier.Bind( "tcp://127.0.0.1:9293" ); while( true ) { Weather weather = new Weather { zipcode = 60645, temperature = 67, humidity = 50 }; CompiledPacker packer = new CompiledPacker( false ); byte[] packWeather = packer.Pack ( weather ); string request = replier.Recv(Encoding.Unicode); Console.WriteLine( request.ToString() ); replier.Send( packWeather ); Weather test = packer.Unpack( packWeather ); Console.WriteLine( "The temp of zip {0} is {1}", test.zipcode, test.temperature ); } } } } 

这是我的C#请求客户端:

 using System; using System.Text; using ZMQ; using MsgPack; namespace zmqMpReq { public class Weather { public int zipcode; public int temperature; public int humidity; } public class zmqMpReq { public static void Main(string[] args) { CompiledPacker packer = new CompiledPacker( false ); Socket requester = new Socket( SocketType.REQ ); requester.Connect( "tcp://127.0.0.1:9293" ); string request = "Hello"; requester.Send( request, Encoding.Unicode ); byte[] reply = null; try { reply = requester.Recv(); } catch( ZMQ.Exception e) { Console.WriteLine( "Exception: {0}", e.Message ); } Weather weather = packer.Unpack( reply ); Console.WriteLine( "The temp of zip {0} is {1}", weather.zipcode, weather.temperature ); System.Threading.Thread.Sleep( 5000 ); } } } 

大多数用任何语言编写的程序都可以通过套接字进行通 所以C#套接字监听器可以监听C ++发送者。 它们通过交换字节序列来实现(非常简化)

你在这里做的是使用字节数组中的 MsgPack序列化C#对象并将其发送出去 。 另一方面,使用相同的MsgPack反序列化C#对象。

这不适用于编程语言,除非您的序列化/反序列化库支持它,在您的情况下MsgPack不支持。

拿这个C#课

 public class Weather { public int zipcode; public int temperature; public int humidity; } 

一个等价的C ++类

  class Weather { public: int zipcode; int temperature; int humidity; } 

根据您的操作系统,C ++中的sizeof(int)将为4个字节(字符)。 C#中的sizeof(int)也是4个字节。

所以理论上你可以在C ++和C#程序之间的套接字连接上交换12 (4 * 3)个字节,这样两边的天气对象几乎是一样的

在C ++中,您应该使用MSGPACK_DEFINE宏,因为您正在处理用户定义的类。 这一切都在MSGPACK网站上的C ++快速入门中进行了解释。

为了使其工作,您必须确保对象中每个属性的类型与不同语言相对应。 这正是MSGPACK的目的,我自己用它来编写一个基于包含MSGPACK对象有效负载的ZeroMQ消息的SQLITE服务器。 最初我使用JSON对象作为消息体,但后来我想以gzipforms发送一个属性,并且在MSGPACK中交换比尝试处理JSON字符串中的二进制数据更容易。

您可能需要阅读http://wiki.msgpack.org/display/MSGPACK/Design+of+Serialization以了解其工作原理。 从概念上讲,它就像将000A00130002转换为“10,19,2”并再次返回。 当然,MSGPACK不使用字符串作为序列化格式,而是使用与语言无关的非常有效的二进制格式。