Pointer to C++ function
-
Is there a way to pass to a C function a pointer to C++ function?
This is the C function
@int wiringPiISR (int pin, int edgeType, void (*function)(void)) ;@My C++ functiin is this:
@QThlpt::OnData;@I can create a pointer to C++ function but the pointer is not valid for a C function.
@ funptr ptr;
ptr= &QThlpt::OnData;
@ -
Hi,
No you cannot pass a pointer-to-non-static-member function, because its type is different. See http://www.parashift.com/c++-faq/fnptr-vs-memfnptr-types.html
- Your C function accepts pointers of type void (*)(void), but
- Your member function's type is void (QThlpt::*)(void)
If your compiler supports C++11, you can use std::bind() or a lambda to create a function of type void (*)(void) that modifies your C++ object. Then, you can pass this function to wiringPiISR()
-
[quote author="JKSH" date="1412506264"]
If your compiler supports C++11, you can use std::bind() or a lambda to create a function of type void (*)(void) that modifies your C++ object. Then, you can pass this function to wiringPiISR()[/quote]Could you give us an example of implementation?
-
In case of someone else wanting to have wiringPiISR() function to work in a class, I wrestled a couple of days with this issue myself. I managed to create a dirty workaround (I know, ew, global pointer) for this, and want to share it to someone who looks for the same thing:
Create static method with your normal method within MyISRClass.h:
public: void myFunction(); static void isrCatcher();
In main.cpp, create global pointer to remember the instance the ISR initialization is in:
MyISRClass *isrClass = 0;
Store the address of the class instance:
extern MyISRClass *isrClass MyISRClass::MyISRClass() { ... isrClass = this; wiringPiISR(pin, INT_EDGE_BOTH, isrCatcher); ... } void MyISRClass ::isrCatcher() { isrClass->myFunction(); }
I hope this helps someone who comes to look for the same answer. I'm a noob with c++, so this probably isn't the safest or even secure way to do this, but it works if you just have to get that Raspberry Pi program to work with simple knowledge.
And don't forget to include LIBS += -L/usr/local/include -lwiringPi -line to your .pro file when compiling.
-
Common pattern for using C callbacks with C++ classes is passing static method (or internal static free function) as a callback pointer, and using
this
as a "data" pointer which is usually passed into callback asvoid*
argument when it's called (in your callback code you cast it into pointer to your class and proceed)static ReturnType A::callbackMethod(<arguments>, void *data) { A* self = static_cast<A*>(data); // Following code uses self instead of this // ... }