小编456*_*26f的帖子

C++ 如何为不了解类实例的 C api 编写包装器?

在我们打算用 C++ 编写的项目中,我们使用 C 库。该 C 库提供了注册回调的函数,这些函数在每次中断时调用。我们在构造函数中注册回调。所以我们基本上有以下(简化的)结构:

OurClass::OurClass() {
  //the registerISRCallback is the C function, that accepts as first parameter the pin,
  //the interrupt is expected on and as second parameter a function pointer:
  //void (*callbackFunction)(int number, int time)
  registerISRCallback(SCLK, handle_interrupt);
}

void OurClass::handle_interrupt(int pin, int time) {
  //example: Blink a Led on the instance-LedPin
}
Run Code Online (Sandbox Code Playgroud)

然而问题是双重的:

  1. 因为它是一个成员函数,所以handle_interrupt方法具有签名void (OurClass::*)(int, int)。因此不可能这样使用它。
  2. 此类可以多次实例化,因此使用单例也不起作用,因为每个实例的回调可能不同(例如,每个实例可能有不同的 LedPin.

有没有更多的解决方案可以在我们的类中使用这个 C API 函数并保持代码干净和可读?

c c++

5
推荐指数
1
解决办法
159
查看次数

标签 统计

c ×1

c++ ×1