Using an object method as a function callback
I am using a C library which has callback functions such as:
int DownloadStream(LPCTSTR host,DWORD channelNumber,NewImage pNewImage);
typedef int (*NewImage)(BYTE *pData, int nLen,void *returnHandle);
In C i can make call like this:
int CallDownloadStream(LPCTSTR host,DWORD channelNumber)
{
int hr = DownloadStream(host,channelNumber,OnNewImage);
return hr;
}
int OnNewImage(BYTE *pData, int nLen,void *returnHandle)
{
// able to get data
}
What i want is call those function as a memb开发者_Python百科er of C++ class such as:
class MyClass
{
public:
int CallDownloadStream(LPCTSTR host,DWORD channelNumber)
{
int hr = DownloadStream(host,channelNumber,OnNewImag);
return hr;
}
int OnNewImage(BYTE *pData, int nLen,void *returnHandle)
{
// able to get data
}
}
I can not able to compile it. Is it possible to use those callback function in that way? If so how can do this?
PS: I have no control over original C style callback functions.
Cannot be done. If the C function does not provide for a user-supplied argument pointer, which is idiomatic in C, then you cannot do this.
Edit: This isn't strictly true. You can use a static variable, you can use thread-local storage, or you can JIT a function. However, those are not general-case solutions.
What you're doing is passing a function pointer so that a C function can call it. In other words, the function pointer you pass has to be callable from C. This means that it needs to be extern "C"
, and cannot be a typical member function. It could be a static
member function, or a free-standing function, but not a class member function.
This means that the callback function can't affect class data members. It can affect static member data, or global data, or whatever else, but not class member data. If this is the effect you were looking for, you need to provide some sort of non-class buffer and shift the data yourself.
It also means that the function passed can't be polymorphic. If you want polymorphic behavior, you need to have all the callback functions you want to pass defined as static
or outside any class, and have the call to the library function in a polymorphic function.
You cannot use non-static member functions as C callback functions.
So the answer is to use a static member function.
You might be able to use libsigc++ - http://libsigc.sourceforge.net/ (look at the documentation for mem_fun). I don't know exactly what would be required in order for it to work properly. Alternatively, make a C call back function which simply calls the proper C++ function using a pointer to the object. (this is probably the easiest way to do this)
精彩评论