已知结构体定义如下:
struct net_buf_simple {
/** Pointer to the start of data in the buffer. */
u8_t *data;
/** Length of the data behind the data pointer. */
u16_t len;
/** Amount of data that this buffer can store. */
u16_t size;
/** Start of the data storage. Not to be accessed directly
* (the data pointer should be used instead).
*/
u8_t __buf[0] __net_buf_align;
};
NET_BUF_SIMPLE宏定义如下:
#define NET_BUF_SIMPLE(_size) \
((struct net_buf_simple *)(&(struct { \
struct net_buf_simple buf; \
u8_t data[_size] __net_buf_align; \
}) { \
.buf.size = _size, \
}))
在某个函数内使用了NET_BUF_SIMPLE宏定义,
比如
void func()
{
struct net_buf_simple *buf = NET_BUF_SIMPLE(29);
...
}
。
那么这个NET_BUF_SIMPLE宏定义表示的啥意思呢?
有点绕。
#define NET_BUF_SIMPLE(_size)
(struct net_buf_simple *)(&(struct {
struct net_buf_simple buf;
u8_t data[_size] __net_buf_align;
})
{
.buf.size = _size,
})
大概意思是:定义一个局部的无名的结构体(包含数据类型struct net_buf_simple和u8_t)变量,为成员变量赋值,然后强制转换为struct net_buf_simple *类型的指针。
测试和验证:
#include <stdio.h>
#include <string.h>
struct net_buf_simple {
/** Pointer to the start of data in the buffer. */
unsigned char *data;
/** Length of the data behind the data pointer. */
unsigned short len;
/** Amount of data that this buffer can store. */
unsigned short size;
/** Start of the data storage. Not to be accessed directly
* (the data pointer should be used instead).
*/
unsigned char __buf[0];
};
#define NET_BUF_SIMPLE(_size) \
((struct net_buf_simple *)(&(struct { \
struct net_buf_simple buf; \
unsigned char data_ext[_size]; \
}) { \
.buf.size = _size, \
}))
#define LEN 10
void main()
{
struct net_buf_simple *net_buf = NET_BUF_SIMPLE(LEN);
printf("len %d, size:%d \n", net_buf->len, net_buf->size);
unsigned char *tmp_buf = ((struct {
struct net_buf_simple buf;
unsigned char data_ext[LEN];
} *)net_buf)->data_ext;
memset(tmp_buf, 's', LEN);
printf("tmp_buf:%s \n", tmp_buf);
}