在C中将匿名结构作为参数传递 [英] Pass anonymous struct as parameter in C

查看:46
本文介绍了在C中将匿名结构作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下c行(为便于阅读,添加了回车符-它们不在代码中):

I have the following line of c (carriage returns added for readability - they aren't in the code):

#define i2c_write(slave_addr, reg_addr, len, *data_ptr)
    twi_master_write(MPU_TWI, {
        .addr = reg_addr,
        .addr_length = 1,
        .buffer = *data_ptr,
        .length = len,
        .chip = slave_addr
    })

其中 twi_master_write()声明为:

uint32_t twi_master_write(Twi *p_twi, twi_packet_t *p_packet);

twi_packet_t 声明为:

typedef struct twi_packet {
    uint8_t addr[3];
    uint32_t addr_length;
    void *buffer;
    uint32_t length;
    uint8_t chip;
} twi_packet_t;

twi_write()的参数都必须为 unsigned char 类型.

The parameters of twi_write() are all required to be of type unsigned char.

编译时,出现以下错误:

When compiling, I receive the following error:

expected expression before '{' token

是否有正确的方法来做我在这里尝试做的事情,或者只是不可能?

Is there a correct way to do what I'm trying to do here, or is it just not possible?

推荐答案

这是编写宏的一种更具可读性和正确性的方法.它可以在 if/else 子句的所有情况下工作,并且该结构在范围内定义,因此它的名称是本地的,不会污染您的名称空间.

Here's a more readable and correct way to write the macro. It will work in all cases of if/else clauses and the struct is defined within a scope so it's name is local and doesn't pollute your name space.

#define i2c_write(_slave_addr, _reg_addr, _len, _data_ptr)  \
    do {                                                    \
    twi_packet_t temp = {                                   \
        .addr = _reg_addr,                                  \
        .addr_length = 1,                                   \
        .buffer = _data_ptr,                                \
        .length = _len,                                     \
        .chip = _slave_addr };                              \
                                                            \
    twi_master_write(MPU_TWI, &temp);                       \
    } while (0)

这篇关于在C中将匿名结构作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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