如何从 C# ZeroMQ 中的消息中提取数据? [英] How to extract data from message in C# ZeroMQ?

查看:35
本文介绍了如何从 C# ZeroMQ 中的消息中提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据从 C++ 发送到 C#.

I need to send data from C++ to C#.

C++ 端,在 Linux 下,我使用 ZMQversion 4.1.4.

On C++ side, under Linux, I am using ZMQ library version 4.1.4.

C# 端正在使用 clrzmq4 基于4.1.5 版本的库.

C# side is using clrzmq4 library based on 4.1.5 version.

所以我在C++中发送消息的部分:

So the part where I send message in C++:

char tempStr[] = "ABCD";
zmq_msg_t zmsg;
zmq_msg_init_size(&zmsg, 4);
memcpy(zmq_msg_data(&zmsg), tempStr, 4);
int rc = zmq_send(reqSocket, &zmsg, sizeof(zmsg), 0);
zmq_msg_close(&zmsg);

C# 获取消息的代码:

ZFrame request = responder.ReceiveFrame();
byte[] reqBytes = new byte[100];
int n = request.Read(reqBytes, 0, 100);

问题是字节数​​组包含 zmq_msg_t 的所有 64 个字节.实际数据从偏移量 16 开始.

The problem is that byte array is including all 64 bytes of zmq_msg_t. The actual data is starting from offset 16.

问题 - 在这种情况下如何正确提取数据?通过硬编码在我的代码中提取偏移量非常难看,因为有一天 zmq_msg_t 可能会从发送方更改,而数据将位于其他地方.另一个选择是避免使用 zmq_msg_t,当双方不使用相同的平台/框架时.在 clrzmq4 框架中,我可以看到 zmq_msg_t 类型的委托,但不确定如何使用它们以及它们是否打算用于公共用途.

Question - how to properly extract data in this case? Extracting by hard coding the offset in my code is simply ugly, because one day zmq_msg_t may be changed from sender side and data will be located somewhere else. Other option is to avoid using zmq_msg_t, when both sides are not using same platform/framework. In the clrzmq4 framework I can see there are delegates for zmq_msg_t types, but not sure how to use them and whether they intended for public usage.

推荐答案

您在 C++ 端混合发送类型,如果使用 zmq_msg_t,您不需要具有大小的变体,即发送缓冲区.

Your mixing the send types on the c++ side, if using zmq_msg_t you dont need the variant with a size, thats for sending a buffer.

如果使用缓冲功能

int zmq_send (void *socket, void *buf, size_t len, int flags)

那你应该这样做

zmq_send(reqSocket, tempStr, 4, 0);

但是如果使用 zmq_msg_t 变体

int zmq_msg_send (zmq_msg_t *msg, void *socket, int flags)

那么你应该这样做:

zmq_msg_send (&zmsg, reqSocket, 0);

这篇关于如何从 C# ZeroMQ 中的消息中提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆