我有一个类,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,我想在其中将函数调用映射到getdevice2Value
和setdevice2Value
。
我看了问题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
运算符。
现在我对这些有几个问题:
callback
概念是否适用于我的情况?Component
实例,我就需要注册它们。我该怎么做呢?C
文件中?struct
被采用。我在哪里声明“结构”?我确实尝试在Component.h
文件中声明它,并将其作为extern
文件中的device1_event.c
引入。但是我收到incomplete type
错误。传递回调的经典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普通函数指针。