[英]Pass anonymous struct as parameter in C
I have the following line of c (carriage returns added for readability - they aren't in the code): 我有以下c行(为了便于阅读而添加了回车符 - 它们不在代码中):
#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
})
Where twi_master_write()
is declared as: twi_master_write()
声明为:
uint32_t twi_master_write(Twi *p_twi, twi_packet_t *p_packet);
and twi_packet_t
is declared as: 和
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;
The parameters of twi_write()
are all required to be of type unsigned char
. twi_write()
的参数都必须是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? 有没有正确的方法来做我想在这里做的事情,还是只是不可能?
My take on it, in a compilable sample. 我在一篇可编辑的样本中对此进行了研究。 This is a compilation stub and will not run correctly , so don't try to run it as-is !
这是一个编译存根, 无法正常运行 ,所以不要试图按原样运行!
//
// Cobbling up a compilation stub
//
#include <stdint.h>
struct Twi;
typedef struct Twi Twi;
#define MPU_TWI (Twi*)0
typedef struct twi_packet {
uint8_t addr[3];
uint32_t addr_length;
void *buffer;
uint32_t length;
uint8_t chip;
} twi_packet_t;
uint32_t twi_master_write(Twi *p_twi, twi_packet_t *p_packet);
//
// Now for my answer :
//
#define i2c_write(slave_addr, reg_addr, len, data_ptr) \
twi_master_write(MPU_TWI, &(twi_packet_t){ \
.addr = reg_addr, \
.addr_length = 1, \
.buffer = *data_ptr, \
.length = len, \
.chip = slave_addr \
})
main()
{
// Trigger that macro !
i2c_write(0, 0, 0, (void**)0);
}
This instanciates a compound literal and passes its address to the function. 这会生成复合文字 ,并将其地址传递给函数。 The literal's lifetime does not exceed that of the full call expression.
文字的生命周期不超过完整调用表达式的生命周期。
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. 它适用于
if/else
子句的所有情况,并且结构在范围内定义,因此它的名称是本地的,不会污染您的名称空间。
#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)
It would be better if you provide a simple complete set of a code, so that we can execute here and help you. 如果您提供一组简单的完整代码会更好,这样我们就可以在这里执行并帮助您。 Meanwhile, i dont think you can use the '*' in the macro, since, macro patameters are not typed.
同时,我不认为你可以在宏中使用'*',因为,没有键入宏参数。 What macro does is just a substitution of a symbol.
宏的作用只是符号的替代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.