मेरे पास एक सी लाइब्रेरी फ़ंक्शन है जो कॉलबैक के लिए फ़ंक्शन पॉइंटर की अपेक्षा करता है, और मैं एक C++ सदस्य फ़ंक्शन में पास करना चाहता हूं। सी ++ फ़ंक्शन एक सदस्य चर को संशोधित करता है, इसलिए मैं एक स्थिर मुक्त फ़ंक्शन का उपयोग नहीं कर सकता (जैसा कि कई समान पदों में सुझाया गया है)। मेरा प्रयास (नीचे दिखाया गया) एक कंपाइलर त्रुटि के साथ विफल रहता है।सी ++ वर्ग सदस्य फ़ंक्शन का उपयोग करना (सी स्थिर नहीं हो सकता है) सी कॉलबैक फ़ंक्शन
इस पोस्ट के सबसे करीब आता है कि मैं क्या जरूरत है:
Using a C++ class member function as a C callback function
मैं इस स्थिर कार्यों के बिना कर सकते हैं? धन्यवाद!
test.h
#ifndef TEST_H_
#define TEST_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*handler_t)(int foo, void *bar);
void set_handler(handler_t h);
#ifdef __cplusplus
}
#endif
#endif
test.c
#include "test.h"
#include <stdlib.h>
static handler_t handler_ = NULL;
void set_handler(handler_t h) {
handler_ = h;
}
void handle_event(int foo, void *bar) {
if (handler_ != NULL) handler_(foo, bar);
}
test.cpp
#include "test.h"
#include <iostream>
using namespace std;
class Foo {
public:
Foo() : ctr_(0) {};
// handler needs to access non-static variable, so it can't be static
void handler(int foo, void *bar) { ++ctr_; }
private:
int ctr_;
};
int main(int argc, char **argv) {
// error: can't convert to "void (*)(int, void*)"
set_handler(&Foo::handler);
cout << "done" << endl;
return 0;
}
जीसीसी barf
$ gcc test.cpp test.c
test.cpp: In function ‘int main(int, char**)’:
test.cpp:18: error: cannot convert ‘void (Foo::*)(int, void*)’ to ‘void (*)(int, void*)’ for argument ‘1’ to ‘void set_handler(void (*)(int, void*))’
क्या आप समझा सकते हैं कि हैंडलर फ़ंक्शन के पैरामीटर क्या हैं? क्या आप यह निर्दिष्ट करते हैं कि इनमें से कोई भी अलग सेटटर या कुछ भी है? –
[यह एक समस्या क्यों है] (http://stackoverflow.com/questions/1707575/c-static-function-wrapper-that-routes-to-member-function/1707678#1707678) –
आपके पास वास्तव में क्या पास हो जाता है 'हैंडलर' समारोह? क्या आप शायद उस कॉलबैक हैंडलर के हस्ताक्षर को बदल सकते हैं या आप उस पुस्तकालय द्वारा प्रदान की जाने वाली चीज़ों का उपयोग करने के लिए बाध्य हैं? – Xeo