使用回调从C调用C ++类方法

问题描述 投票:0回答:1

我有一个类,Component,它必须与C代码进行交互。

//// Component.h file   ////
class Component{
public:
    uint8_t getdevice1Value();
    void setdevice1Value(uint8_t value);

    uint8_t getdevice2Value();
    void setdevice2Value(uint8_t uint8_t);
private:
    uint8_t device1Value;
    uint8_t device2Value;
}

在某些Application.cpp文件中创建其相关线程时,将创建该类的对象:

///////Some function where the Component is used//////
createThread(){
    Component myComponent;  // Scope within the thread
    // Some actions
}

现在是我的C代码,它恰好是事件驱动的。在这些函数中,我想链接我的Class方法:

//// device1_event.c file   ////
void command_get_device_value()
{
    // code
    // assign variable  = Component::getdevice1Value() function
    // code
}

void command_set_device_value()
{
    // code
    // call Component::setdevice1Value(variable)  passing some variable
    // code
}

类似于device1_event.c文件,我还有另一个device2_event.c,我想在其中将函数调用映射到getdevice2Valuesetdevice2Value

我看了问题Using a C++ class member function (cannot be static) as a C callback function或这个Pass a C++ member function to a C function,其中struct注册了上下文和函数指针。

在无法动态分配的情况下,我受到了限制。因此,我无法使用new运算符。

现在我对这些有几个问题:

  1. callback概念是否适用于我的情况?
  2. 如果第一个问题是肯定的,那么:
    • 我该如何实施它。我对此有些困惑。我的意思是调用函数需要放置在C函数中,并且一旦创建Component实例,我就需要注册它们。我该怎么做呢?
    • 如何将回调函数带到我的C文件中?
  3. In this question a struct被采用。我在哪里声明“结构”?我确实尝试在Component.h文件中声明它,并将其作为extern文件中的device1_event.c引入。但是我收到incomplete type错误。
c++ c c++11 callback
1个回答
0
投票

传递回调的经典C方法是传递two值:指向回调本身的指针,以及不透明的指针,它将作为附加参数传递给回调(请参阅qsort_r例)。与C ++接口时,该不透明值可以用作实例指针。您只需要编写一个薄包装器即可:

class B {
    void my_callback(int arg);
    static void my_callback_wrapper(int arg, void *u) {
        (B*)u->my_callback(arg);
    }
};

// or even:
extern "C" void my_callback_wrapper(int arg, void *u) {
    (B*)u->my_callback(arg);
}

并将指向包装器的指针以及指向对象的指针传递到C部分。请小心在两侧使用完全相同的类类型,而不要使用基类/派生类。

[请注意,虽然有可能获得指向(非静态)方法本身的指针,但在某些编译器(很久以前已在MSVC上进行测试)上,它们具有特殊的调用约定,因此该指针将与any普通函数指针。

© www.soinside.com 2019 - 2024. All rights reserved.