gpt4 book ai didi

c++ timer implemetation - 分配一个成员函数来通知回调函数指针

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:18 24 4
gpt4 key购买 nike

嗨,我一直在尝试使用 posix 计时器库来实现计时器,但我在实现时犯了一个错误,我使用了来自网络的示例并尝试封装在一个类中,但是编译器不喜欢它,基本上尝试将回调函数分配给 sigev.sigev_notify_function = TIMER0_IRQHandler; 但我得不到任何结果。代码如下:

类定义:

#include <sys/time.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
//se agrego para eliminar el siguiente warning del compilador
//warning: incompatible implicit declaration of built-in function 'memset'
#include <string.h> /* memset */
#include <unistd.h> /* close */


#define TIMEVAL_MAX 0xFFFFFFFF
#define TIMEVAL unsigned int
// The timer is incrementing every 4 us.
//#define MS_TO_TIMEVAL(ms) (ms * 250)
//#define US_TO_TIMEVAL(us) (us>>2)

// The timer is incrementing every 8 us.
#define MS_TO_TIMEVAL(ms) ((ms) * 125)
#define US_TO_TIMEVAL(us) ((us)>>3)

class Timer
{
public:
Timer();
void initTimer();
void setTimer(TIMEVAL aValue);
TIMEVAL getElapsedTime( void ) ;
void TIMER0_IRQHandler(sigval_t val);
private:
struct timeval last_sig;
timer_t timer;

};

以及与编译器冲突的函数:

void Timer::initTimer()
{
struct sigevent sigev;

// Take first absolute time ref.
if(gettimeofday(&last_sig,NULL)){
perror("gettimeofday()");
}

memset (&sigev, 0, sizeof (struct sigevent));
sigev.sigev_value.sival_int = 0;
sigev.sigev_notify = SIGEV_THREAD;
sigev.sigev_notify_attributes = NULL;
sigev.sigev_notify_function = &TIMER0_IRQHandler;

if( timer_create (CLOCK_REALTIME, &sigev, &timer)) {
perror("timer_create()");
}

}
*//callback function
void Timer::TIMER0_IRQHandler(sigval_t val)
{
if(gettimeofday(&last_sig,NULL)) {
perror("gettimeofday()");
}
printf("TIMER NOTIFY\n");
}

提前致谢!

最佳答案

要调用成员函数,您还需要指向this 的指针,这意味着您不能直接执行此操作。但是,您可以使用静态函数作为回调的包装器,它可以提取 this 指针并调用您的真实回调:

class Timer
{
public:
static void handler_wrapper(sigval_t val);
void handler();
};

void Timer::handler_wrapper(sigval_t val)
{
Timer *object = (Timer *)val.sival_ptr;
object->handler();
}

void Timer::handler(void)
{
// do whatever. just remember what thread context you're in
}

// in main
sigev.sigev_value.sival_ptr = (void*) this;
sigev.sigev_notify_function = &Timer::handler_wrapper;

关于c++ timer implemetation - 分配一个成员函数来通知回调函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com