[英]Calling c++ object in callback function of c library
I am using a C library, which uses callback functions.我正在使用一个使用回调函数的 C 库。
Is there any way I can access calling object of C++ class?有什么方法可以调用 object 的 C++ class?
Edit:编辑:
I am using c-client lib.我正在使用 c-client 库。 Which have function mm_log.
其中有 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.
我想检查它被调用的是哪个 Imap stream。
More Info you can download library from ftp://ftp.cac.washington.edu/imap更多信息,您可以从ftp://ftp.cac.washington.edu/imap下载库
All (good) C library functions that want a callback have a void* user_data
pointer as part of the function and the callback parameter.所有需要回调的(好)C 库函数都有一个
void* user_data
指针作为 function 和回调参数的一部分。 You just pass a pointer to your object as this to the function and it just gets passed back to you in the callback.您只需将指向 object 的指针传递给 function ,它就会在回调中传回给您。 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);
}
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.如果
mm_log
是您正在实现的 function 并且库正在调用(顺便说一句,这是库进行回调的一种糟糕方式),那么您无法让它引用 function 中的 ZC61DZAB.
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.你可以做的是在调用库之前使用一个全局变量来指向你的 object (并在之后清除),然后在
mm_log
中使用它来调用所需的方法。 This is nasty and dangerous but can work.这是令人讨厌和危险的,但可以工作。
If you have more than one thread then exercise extreme caution - or find a better library.如果你有多个线程,那么要格外小心——或者找一个更好的库。
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:您必须使用访问普通旧结构的全局函数来包装 C++ object,并使用以下命令导出:
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请参阅此常见问题解答: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.