gpt4 book ai didi

c++ - 结构的地址是否与其第一个成员的地址相同?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:32 25 4
gpt4 key购买 nike

考虑我有如下结构:

struct Bitmask
{
unsigned char payload_length: 7;
unsigned char mask: 1;
unsigned char opcode: 4;
unsigned char rsv3: 1;
unsigned char rsv2: 1;
unsigned char rsv1: 1;
unsigned char fin: 1;
};

const char* payload = "Hello";
const size_t payload_length = strlen(payload);

Bitmask* header = new Bitmask();
header->fin =1;
header->rsv1 = 0;
header->rsv2 = 0;
header->rsv3 = 0;
header->opcode = 1;
header->mask = 0;
header->payload_length = payload_length;

iovec iov[2];
iov[0].iov_base = (char*)header;
iov[0].iov_len = sizeof (header);
iov[1].iov_base = (char *)payload;
iov[1].iov_len = strlen(payload);

ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("iov[0].length = %d\niov[1].length = %d\n"),
iov[0].iov_len,
iov[1].iov_len));

size_t bytes_xfered;
client_stream_.sendv_n (iov, 2, 0, &bytes_xfered);

cout << "Transfered " << bytes_xfered << " byte(s)" << std::endl;

我正在用适当的值对其进行初始化。最后,我想将结构转换为 char* 以便我可以附加我的有效负载(即 char* 消息)并通过 websocket 连接发送它。

最佳答案

Is a struct's address the same as its first member's address?

是的,这实际上是 C 和 C++ 标准强制要求的。来自 C 标准:

6.7.2.1-13. A pointer to a structure object, suitably converted, points to its initial member

struct 的大小应该是两个字节。但是,您不应该将指向它的指针转换为 char*:相反,您应该使用 memcpy将您的 Bitmask 复制到您通过网络发送的缓冲区中。

编辑 因为您使用iovec 的分散-聚集 I/O,您不需要将Bitmask 转换为任何东西: iov_basevoid*,因此您可以简单地设置 iov[0].iov_base = header;

注意:这仅在您的 struct 不包含虚函数、基类等时有效(感谢 Timo)。

EDIT2

为了在您的 struct 中获得 {0x81, 0x05},您应该按如下方式更改结构元素的顺序:

struct Bitmask {
unsigned char opcode: 4;
unsigned char rsv3: 1;
unsigned char rsv2: 1;
unsigned char rsv1: 1;
unsigned char fin: 1;
unsigned char payload_length: 7;
unsigned char mask: 1;
}

关于c++ - 结构的地址是否与其第一个成员的地址相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9254605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com