在c代码中注册一个c++回调方法

Registering a c++ callback method in a C code

本文关键字:一个 c++ 回调 方法 代码 注册      更新时间:2023-10-16

我有一个c++类和c代码。以下是粗略的(逻辑上相同)和最小化的代码

// C++ class - Car.cpp
void Car :: initialise() 
{ 
  WheelT mWheel;   // WheelT is a struct in Wheel.c
  mWheel.run(wheelGotFlat);    // <---- I want to pass here the c++ callback method , so that if the             wheel goes flat , the callback should hit 
}
static void car :: wheelGotFlat()   // <--- callback method
{
}
// C code - Wheel.c
void checkStatus(callback aCb)
{
   // if wheel is flat 
   // ----- here I want to hit the callback method that was passed as argument to run()
}
void run(callback aCb)
{                      
    checkStatus(aCb);       
}

怎么做??

要使c++函数可以从C中调用,例如使用extern "C" void foo(int) { ... }。要使它调用成员函数,必须使回调成为一个用c++编写的存根,但可以从C中调用,然后调用成员函数。

请注意,使用静态成员函数通常可以工作,但实际上是未定义的行为。