将类成员绑定到plain-C函数指针
Bind class member to plain-C function pointer
我有一个库,其中的源代码我不能更改。它有一个包含函数指针的结构,这是一些事件的回调。考虑:
// library code (.h file)
typedef int (callback_function)(int arg1, double arg2);
struct callbacks_struct
{
...
callback_function *callback;
...
};
我正在为这些低级的东西写一个c++包装器。假设我有一个类:
class Wrapper
{
public:
int Callback(int arg1, double arg2);
};
现在我想绑定Wrapper::Callback
在创建结构callback_struct
时用作回调:
struct callback_struct x[] =
{
{
...
// put a Wrapper::Callback as a callback
...
},
{0, 0, 0, 0}
}
显然,如果没有一些中间函数,这是不可能完成的。一种方法是创建一个Wrapper
类的全局对象并使用它:
std::shared_ptr<Wrapper> gWrapper;
void foo()
{
struct callback_struct x[] =
{
{
...
my_plain_callback,
...
},
{0, 0, 0, 0}
}
}
int my_plain_callback(int arg1, double arg2)
{
return gWrapper->Callback(arg1, arg2);
}
但是我需要一个线程安全的解决方案,所以在这种情况下使用全局变量似乎是问题的根源。
谁知道更好的解决方案?
谢谢。
为回调状态使用线程本地变量
或者走核心路线,使用一些平台相关的代码来生成注入指针的存根。
它可能对你有帮助:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <stdexcept>
#include <mutex>
class Wrapper
{
typedef std::mutex mutex_type;
typedef std::unique_lock<mutex_type> locker;
public:
typedef boost::function<int(int,double)> call_backtype;
static int callBackFunction(int arg1_, double arg2_)
{
locker l(_mutex);
if ( my_call.empty() ) {
throw std::runtime_error("No callback function was set!");
}
return my_call(arg1_,arg2_);
}
static void setCallBack( const call_backtype& func_ )
{
locker l(_mutex);
_my_call = func_;
}
private:
static mutex_type _mutex;
static call_backtype _my_call;
Wrapper(void){}
};
class any_other_class
{
int do_anything(int arg1_, double arg2_);
void setThisAsCallback()
{
Wrapper::setCallBack(boost::bind(&any_other_class::do_anything,this,_1,_2));
}
};
// to C interface (use the static method):
setCallBack(&Wrapper::callBackFunction);
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 将类成员绑定到plain-C函数指针