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

标签 c++ linux timer

嗨,我一直在尝试使用 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/

相关文章:

c# - 为什么我的委托(delegate)只使用我的 foreach 循环中的最后一项?

c++ - C++ 枚举类可以有方法吗?

java - 解压缩大文件(~80 GB)- 使用 Java 或 shell 脚本

c++ - 使用 GetProcessTimes 在 Windows 上测量 CPU 时间

linux - 无法连接到远程 mongodb 服务器

linux - 如何过滤掉文件中的所有唯一行?

java - 如何设置 block 超时?

c++ - 常量成员函数可变

c++ - C++中的哈希表?

c++ - 为什么 *must* delete[] 和 delete 是不同的?