This may have been a little bit of a complicated project to start with especially since I knew nothing about C++ but I'm enjoying it (for the most part).
I've got another problem, with probably a simple fix, I just don't know how to. Due to the fact that I decided to support two different architectures for my program, the Bluetooth libraries I use differ significantly. One of the big differences is that one has built in callback, and the other doesn't. Because of the major differences I often create a class that will allow me to run a function that performs differently depending on the hardware.
Here's a dumbed down version of a bit of code I have:
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
|
typedef void (*Callback)(const char *data);
void _callback(const char *data) {
Serial.println(data); //On setup, this will print "test1". It will never print "print me" however.
}
#ifdef A
class CallBack : public BLECharacteristicCallbacks
{
Callback *x;
public:
CallBack();
CallBack(Callback *cb) {
x = cb;
(*x)("test1");
};
void onWrite() {
(*x)("print me"); //Depending on how I pass down the function (ie. pointers, the object itself) this sometimes causes a crash.
};
};
#else
class Callback {
.....
};
#endif
class Bluetooth
{
Callback *x;
public:
Bluetooth();
void setup() {
CallBack(x); //Do something with this
};
void createCallback(Callback *cb) {
x = cb;
};
};
class MainClass
{
Bluetooth b;
public:
MainClass();
void setup() {
b.setup();
};
void setCallback(Callback cb) {
b.createCallback(&cb);
}
};
|
(The main class, in my program, is in a separate file).
It is run by firstly calling "setCallback". In this case, I pass in "_callback" as the argument. This sets the "x" variable of Bluetooth to a pointer to that function.
"setup" is then called, which calls Bluetooth's setup function, which in turn creates an instance of the Callback class, with the function pointer as a argument.
In the constructor of the Callback class I call that function with "test". When looking at the console I see "test". However, once onWrite is called (which is called when Bluetooth receives data), it will either do nothing / crash the program.
I read somewhere that once a function has returned, the pointer to that function becomes invalid or something along those lines. If that's the case then once the Main class "setup" function has returned, the pointer to "_callback" is no longer going to be valid which is why when "onWrite" is called, it crashes or does nothing.
What's a better way of doing this?