How to implement a callback function
Hello,
I would like to properly implement a callback function, but I have no idea how. I am trying to make a DLL, for now this DLL should have a number of variables that are stored in a 2D array. Using the set function in the interface I can select a variable in this 2D array (row and column index) and change its value.
Using the get function I can verify that the change was successful, but I would like to be notified about this change automatically. I have been told this could be done using a callback function, but I have no idea how to implement that.
Could somebody please provide me with an example and/or explanation for a proper implementation to trigger the callback function if one of the values in the 2D array changes and how to catch the resulting event?
Many thanks in advance, Nico
Code:
#pragma once
#if !defined(DLL)
#define DLL __declspec(dllimport)
#endif
#if !defined(IDLL)
#define IDLL DLL
#endif
#if defined(__cplusplus)
extern "C" {
#endif
// callback function
// long EventType: Not sure what kind of event types are available
// long Column: The column.
// long Row: The row.
// long EventCode: e.g. 0 = decreased, 1 = increased
// long EventDataLong: Not sure, but I was told we would need a parameter.
// double EventDataDouble : The current value of the variable
typedef void (__stdcall *OnExampleParameterChangedEvent)(long EventType,
long Column,
long Row,
long EventCode,
long EventDataLong,
double EventDataDouble);
// Attach callback function handler
IDLL long __stdcall ExampleAttachParameterChangedEvent(OnExampleParameterChangedEvent ParameterChanged);
// Read the state of a Value.
// long Column: The column.
// long Row: The row.
// long* State: The state of the parameter
IDLL long __stdcall ExampleGetValue(long Column, long Row, long* State);
// Sets the state of a Value.
// long Column: The column.
// long Row: The row.
// long State: The state of the parameter
IDLL long __stdcall ExampleSetValue(long Column, long Row, long State);
#if defined(__cplusplus)
}
#endif
Re: How to implement a callback function
This is a very simple example of using a callback function
Code:
#include <string>
#include <iostream>
using namespace std;
void fcb1()
{
cout << "In call 1" << endl;
}
void fcb2()
{
cout << "In call 2" << endl;
}
class cbck
{
typedef void(*fc)();
string s1;
fc fcb;
public:
cbck(fc fb = fcb1) : fcb(fb) {}
string getstr() const
{
return s1;
}
void setstr(const string& s) {
s1 = s;
fcb();
}
void setcall(fc fb)
{
fcb = fb;
}
};
int main()
{
cbck c1;
c1.setstr("s1");
cout << c1.getstr() << endl;
c1.setcall(fcb2);
c1.setstr("s2");
cout << c1.getstr() << endl;
}