Reputation: 24140
I am using a C library, which uses callback functions.
Is there any way I can access calling object of C++ class ?
Edit:
I am using c-client lib. Which have function mm_log.
void mm_log(char* string, long err_flag)
which is getting internally called by library. I want to check on which Imap stream it is getting called.
More Info you can download library from ftp://ftp.cac.washington.edu/imap
Upvotes: 0
Views: 2465
Reputation: 18964
If mm_log
is a function which you are implementing and the library is calling (which is a terrible way for a library to do callbacks, by the way), then there is no way you can get it to reference a member function in your class.
What you could do is use a global variable which you set to point to your object before invoking the library (and clear after) and then use it within mm_log
to invoke the desired method. This is nasty and dangerous but can work.
If you have more than one thread then exercise extreme caution - or find a better library.
Upvotes: 1
Reputation: 59101
Code is important for such a question. But without seeing any of your code, I can still give you a blanket statement :)
You'd have to wrap your C++ object with global functions that access a plain-old-struct, and export those with:
extern "C"
There are a plenty of caveats, but this is the gist of it.
See this FAQ: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html
Upvotes: 0
Reputation: 131789
All (good) C library functions that want a callback have a void* user_data
pointer as part of the function and the callback parameter. You just pass a pointer to your object as this to the function and it just gets passed back to you in the callback. Example:
typedef void (*callback)(void*);
void dumb_api_call(callback cb, void* user_data){
cb(user_data);
}
struct Foo{};
void my_callback(void* my_data){
Foo* my_foo = static_cast<Foo*>(my_data);
}
int main(){
Foo my_foo;
dumb_api_call(my_callback, &my_foo);
}
Upvotes: 3