英文:
Can't pass object into function
问题
所以我正在尝试制作一个程序,用于提供树莓派和加速度计/陀螺仪之间的接口。我需要这个函数尽可能频繁地更新,并且我想设置一个定时器来运行它。
以下是我的代码:
void updateGyro(Gyro gyro) {
gyro.update();
}
int main() {
if (gpioInitialise() < 0)
return -1;
// 创建新的陀螺仪对象
Gyro gyro;
// 设置一个定时器,每10毫秒更新一次
gpioSetTimerFuncEx(0, 10, updateGyro, &gyro);
time_sleep(10);
gpioTerminate();
}
但这似乎不起作用,我得到了错误:
gyro.cpp: In function ‘int main()’:
gyro.cpp:113:31: error: invalid conversion from ‘void (*)(Gyro)’ to ‘gpioTimerFuncEx_t’ {aka ‘void (*)(void*)’} [-fpermissive]
113 | gpioSetTimerFuncEx(0, 10, updateGyro, &gyro);
| ^~~~~~~~~~
| |
| void (*)(Gyro)
In file included from gyro.cpp:2:
/usr/include/pigpio.h:3751:55: note: initializing argument 3 of ‘int gpioSetTimerFuncEx(unsigned int, unsigned int, gpioTimerFuncEx_t, void*)’
3751 | unsigned timer, unsigned millis, gpioTimerFuncEx_t f, void *userdata);
| ~~~~~~~~~~~~~~~~~~^
我尝试将gyro.update
函数直接传递给函数,但也没有起作用。有人知道如何修复这个问题吗?
英文:
So I'm trying to make a program to provide a interface between a raspberry pi and a accelerometer/gyroscope. I need this function to update as often as possible and I want to set a timer for when it will run.
And here is my code:
void updateGyro(Gyro gyro) {
gyro.update();
}
int main() {
if (gpioInitialise() < 0)
return -1;
// Creates new gyro object
Gyro gyro;
// Sets a timer to update every 10 milliseconds
gpioSetTimerFuncEx(0, 10, updateGyro, &gyro);
time_sleep(10);
gpioTerminate();
}
But this doesn't seem to work and I get the error:
gyro.cpp: In function ‘int main()’:
gyro.cpp:113:31: error: invalid conversion from ‘void (*)(Gyro)’ to ‘gpioTimerFuncEx_t’ {aka ‘void (*)(void*)’} [-fpermissive]
113 | gpioSetTimerFuncEx(0, 10, updateGyro, &gyro);
| ^~~~~~~~~~
| |
| void (*)(Gyro)
In file included from gyro.cpp:2:
/usr/include/pigpio.h:3751:55: note: initializing argument 3 of ‘int gpioSetTimerFuncEx(unsigned int, unsigned int, gpioTimerFuncEx_t, void*)’
3751 | unsigned timer, unsigned millis, gpioTimerFuncEx_t f, void *userdata);
| ~~~~~~~~~~~~~~~~~~^
I've tried passing in the gyro.update function in directly into the function but that also didn't work. Does anyone know how to fix this?
答案1
得分: 6
void*
不是任何数量或类型参数的占位符。它确切地表示单个指向未知类型的指针。updateGyro
不接受类型为 void*
的参数,它接受类型为 Gyro
的参数。
您需要更改您的函数以接受 void*
,如下所示:
void updateGyro(void* arg) {
Gyro* gyro = static_cast<Gyro*>(arg);
gyro->update();
}
英文:
void*
is not a placeholder for any number of any arguments. It means exactly that, single pointer to unknown type. updateGyro
doesn't accept argument of type void*
, it accepts argument of type Gyro
.
You need to change your function to accept void*
instead:
void updateGyro(void* arg) {
Gyro* gyro = static_cast<Gyro*>(arg);
gyro->update();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论