是否可以绑定()*这类的成员函数,使回调到C API [英] Is it possible to bind() *this to class member function to make a callback to C API
问题描述
有没有使用升压或性病的bind(),所以我可以使用结果作为C API回调的方法吗?
这里的样本code我使用:
Is there a way to use boost or std bind() so I could use a result as a callback in C API? Here's sample code I use:
#include <boost/function.hpp>
#include <boost/bind/bind.hpp>
typedef void (*CallbackType)();
void CStyleFunction(CallbackType functionPointer)
{
functionPointer();
}
class Class_w_callback
{
public:
Class_w_callback()
{
//This would not work
CStyleFunction(boost::bind(&Class_w_callback::Callback, this));
}
void Callback(){std::cout<<"I got here!\n";};
};
谢谢!
推荐答案
没有,有没有办法做到这一点。问题是,一个C函数指针基本上是没有什么比一个指令地址更多:去这个地址,并执行你发现的说明。的要带入函数的任何的状态都有要么是全球性的,或作为参数传递。
No, there is no way to do that. The problem is that a C function pointer is fundamentally nothing more than an instruction address: "go to this address, and execute the instructions you find". Any state you want to bring into the function has to either be global, or passed as parameters.
这就是为什么大多数C回调的API有背景的参数,通常是一个空指针,你可以传递,只是用来让你在你需要的数据传递。
That is why most C callback APIs have a "context" parameter, typically a void pointer, that you can pass in, and just serves to allow you to pass in the data you need.
这篇关于是否可以绑定()*这类的成员函数,使回调到C API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!