I'll try to explain my need:
- I have a generic library I created, called
myIOT.h
. - This class have a pre-configured MQTT and wifi setup.
- Inside this library there is a
mqtt_callback
function, for all generic commands, such asboot_time
andconnection_status
. - BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that
iot.mqtt_callback(ext_mqtt_func)
will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.
I'll try to explain more clearly:
void myIOT::mqtt_callback(ext_mqtt_func){
if (a == true ) {
do something
};
else {
ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library
}
Michel Keijzers
13k7 gold badges41 silver badges58 bronze badges
asked Jan 11, 2019 at 19:26
-
Note that it is better to use if (a) than comparing a boolean with true or false. If you name a better so it is clear it is a boolean it is better maintainable.Michel Keijzers– Michel Keijzers2019年01月11日 22:51:17 +00:00Commented Jan 11, 2019 at 22:51
-
@MichelKeijzers it is a string compare function to set a MQTT commanguyd– guyd2019年01月12日 06:00:46 +00:00Commented Jan 12, 2019 at 6:00
1 Answer 1
Yes, you can do it.
You pass function pointer as function parameter.
See this stackoverflow question:
https://stackoverflow.com/questions/2582161/c-function-pointer-as-parameter
-
thank you, it works great. Since it have to a string using a MQTT, this ext_fuct needs as well to pass this string - and the explanation above is for a no-arg function, so I did upgrade it to be
typedef void (*cb_func)(char msg1[50])
that passes its string ( and it works great ), but I would rather pass it as a pointer to that string ( which fails )guyd– guyd2019年01月12日 06:28:41 +00:00Commented Jan 12, 2019 at 6:28
lang-cpp