问题描述
在C ++项目中,我使用C库访问一些硬件。 C-Bindings包括回调以通知一些输入引脚上的更改。
回调函数看起来像这样:
void callback(char port,uint8_t interrupt_mask,uint8_t value_mask,void * user_data)
In a C++ project I am using a C library to access some hardware. The C-Bindings include callbacks to notify about changes on some input pins.The function for the callback looks like this:void callback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data)
在我的实现中,我有一个 SensorController
类,它有一个成员函数应该接收回调。成员函数看起来像这样 void SensorController :: pinChanged(char port,uint8_t interrupt_mask,uint8_t value_mask,void * user_data)
。
In my implementation I have a SensorController
class which has a member function that should receive the callback. The member function looks like this void SensorController::pinChanged(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data)
.
现在我想知道,什么是最简单的方法,避免使 pinChanged
function static能够将函数分配给回调?
Now I was wondering, what would be the cleanest way to avoid making the pinChanged
function static to be able to assign the function to the callback?
推荐答案
使用 user_data
指针返回指向拥有回电话。例如
Use the user_data
pointer to give you back a pointer to the class that owns the callback. For example.
void MyCallback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data)
{
static_cast<Example *>(user_data)->Callback(port, interrupt_mask, value_mask);
}
class Example
{
public:
Example()
{
//setup callback here - i dont know what library you're using but you should be able to pass a this pointer as user_data
init_lib(fictionalparameter1, fictionalparameter2, this);
}
private:
void Callback(char port, uint8_t interrupt_mask, uint8_t value_mask)
{
//callback handler here...
}
friend void MyCallback(char port, uint8_t interrupt_mask, uint8_t value_mask, void *user_data);
};
这篇关于将C ++成员函数映射到C回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!