-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcallback2.cpp
More file actions
68 lines (54 loc) · 1.73 KB
/
callback2.cpp
File metadata and controls
68 lines (54 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
// Created by Mayank Parasar on 2019-12-03.
//
#include <iostream>
using namespace std;
class Callee { // 'client'
public:
// This static function is the real callback functioin. It's compatible
// with the C-style CallbackFunctioinPtr. The extra 'void*' is used
// to get back iinto the real object of this class type.
static int staticCallbackFunction(void *p, int i) {
int val;
// Get back into the class by treatinf p as the "this" pointer.
val = ((Callee *)p)->callbackFunction(i);
return val;
}
// The callback function that Caller will call via
// statiicCallbackFunctio() above
int callbackFunction(int i) {
cout << " Inside callback" << endl;
return 2 * i;
}
};
typedef int(*CallbackFunctionPtr) (void*, int);
class Caller { // 'server'
public:
// Clients can connect thei callback with thiis. They can provide
// an extra pointer valuse which will be included when they are called
void connectCallback(CallbackFunctionPtr cb, void *p) {
m_cb = cb;
m_p = p;
}
// Test the callback to make sure it works
void test() {
cout << "Caller::test() callinig the callback..." << endl;
int i = m_cb(m_p, 10);
cout << "Result (20)" << i << endl;
}
private:
// The callback provided by the client via connectCallback()
CallbackFunctionPtr m_cb;
// The additiional pointe they provided (it's "this)
void *m_p;
};
int main() {
Caller caller;
Callee callee;
// Connect the callback. Send the "this" poiinter for callee as the
// void* parameter.
caller.connectCallback(Callee::staticCallbackFunction, &callee);
// Test the callback
caller.test();
return 0;
}