结构的地址与它的第一个成员的地址相同吗? [英] Is a struct's address the same as its first member's address?

查看:96
本文介绍了结构的地址与它的第一个成员的地址相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我的Struct如下:

Consider I have Struct like the following:

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连接发送它.

I am initializing it with appropriate values. Finally, I want to convert the struct into char* so I can append my payload (which is char* message) and send it over a websocket connection.

推荐答案

结构的地址与它的第一个成员的地址相同吗?

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

是的,这实际上是C和C ++标准强制要求的.从C标准开始:

Yes, this is actually mandated by the C and C++ standards. From the C standard:

6.7.2.1-13.适当转换的指向结构对象的指针指向其初始成员

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

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

The size of your struct should be two bytes. You should not convert a pointer to it to char*, though: instead, you should use memcpy to copy your Bitmask into the buffer that you send over the network.

编辑由于您将分散式I/O与iovec结合使用,因此无需将Bitmask强制转换为任何内容:iov_basevoid*,因此您可以简单地进行设置iov[0].iov_base = header;

EDIT Since you use scatter-gather I/O with iovec, you do not need to cast Bitmask to anything: iov_base is void*, so you can simply set iov[0].iov_base = header;

注意:仅当struct不包含虚函数,基类等(谢谢蒂莫)时,此方法才起作用.

Note: This works only as long as your struct does not contain virtual functions, base classes, etc. (thanks, Timo).

EDIT2

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

In order to get {0x81, 0x05} in your struct, you should change the order of structure elements as follows:

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

这篇关于结构的地址与它的第一个成员的地址相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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