【发布时间】:2021-03-03 20:20:38
【问题描述】:
我有以下结构:
typedef struct
{
uint8_t number;
uint8_t user_bank;
uint8_t temperature;
float acc_xyz[3];
float gyro_xyz[3];
float mag_xyz[3];
float acc_bias[3];
float gyro_bias[3];
float quaternions[4];
char *orientation_of_IMU;
char *component_orientation_on_pcb;
} Sensor;
我有兴趣将一些浮点成员表示为字节,因此我可以通过 SPI 传输它们。到目前为止,我有这些函数,它们允许我包装 4 个浮点四元数,并在缓冲区中返回 16 个字节。
typedef char byte;
void floatToByteArray(float f, byte buf[4])
{
memcpy(buf, &f, sizeof(f));
}
//Function that takes float quaternions from a sensor struct, and returns their values, represented as bytes for easier SPI transfer.
void wrap_quaternions(Sensor* imu, int8_t *buff)
{
for (int i = 0; i < 4; i++)
{
floatToByteArray(imu->quaternions[i], &buff[4*i]);
}
}
现在我对泛化它很感兴趣,因此我可以在 Sensor 结构中获取我的任何浮点数组成员,并相应地包装它们。我希望能够使用参数为 imu->float_member 调用 floatToByteArray 函数,但我不能这样做。然后我可以将数字 4 更改为 sizeof(float_member)。
有解决办法吗?
【问题讨论】:
-
将
Sensor* imu参数替换为int cnt, float *arr[cnt]。然后你可以传递例如3, sensor->gyro_bias,或者你可以传递sizeof(sensor->gyro_bias)/sizeof(float), sensor->gyro_bias。 -
太棒了!我将添加它,并在我的传感器结构中为包装数据创建一个嵌套结构。然后我将使用参数
sizeof(sensor->acc_bias), sensor ->acc_bias, sensor -> wrapped_data -> acc_bias_wrapped。这应该可行,对吧? -
嗯。我试过了,但它似乎不起作用。也许您可以查看我的其他评论?
-
哎呀,对不起,我搞砸了我的例子。
float *arr[cnt]应该只是参数列表中的float arr[cnt]。
标签: c function pointers struct