我什么时候应该使用 zmq_msg_t?

When I should use zmq_msg_t?

收发消息的函数如下:

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

但是,从文档中不清楚我何时必须直接使用 zmq_msg_t 或我的自定义数据。那么在哪些情况下我应该考虑使用 zmq_msg_t 以及在哪些情况下直接发送我的数据?

永远不会 TLDR

在如何设置时要相当小心,load/unload 和 consume/destroy 支持的低级数据结构,酷而强大 ZeroMQ-图书馆服务依赖。

否则,最好还是使用高级配套函数。


请毫不犹豫地阅读这本书 - 值得花时间

Pieter HINTJENS 在第 42 页第 4 项中推荐:

To release (not destroy) a message, you call zmq_msg_close(). This drops a reference, and eventually 0MQ will destroy the message.

API documentation中你可能会发现更加谨慎:

The zmq_msg_close() function shall inform the ØMQ infrastructure
that any resources associated with the message object
referenced by msg are no longer required and may be released.

Actual release of resources associated with the message object
shall be postponed by ØMQ until all users of the message or underlying
data buffer have indicated it is no longer required.

Applications should ensure that zmq_msg_close() is called
once a message is no longer required, otherwise memory leaks may occur.

切勿直接访问 zmq_msg_t 成员, 而是始终使用 zmq_msg 函数族。

Return value:
              zmq_msg_close() function shall return zero if successful.
                              Otherwise it shall return -1 and
                              set errno to one of the values defined below.
Errors
              EFAULT          Invalid message.

这两个函数都将在内部构造一个 zmq_msg_t,然后使用该函数的 zmq_msg_t 变体。这很方便,但如果您想多次发送相同的消息,创建 zmq_msg_t 并使用这些变体会更有效(减少复制)。