Currently I have a class of this kind, shortened for simplicity:
class MyClass {
public:
MyClass();
void* someFunc(void* param);
}
Now I need to call a function of this kind (not member of any class and which I unfortunately cannot change) but which I need to call anyway:
void secondFunc(int a, int b, void *(*pCallback)(void*));
Now I need to pass the address of someFunc of an instance.
A not working sample:
MyClass demoInstance;
// some other calls
secondFunc( 1, 2, demoInstance::someFunc() );
I've tried also with casts like:
(void* (*)(void*)) demoInstance::someFunc;
reinterpret_cast<(void* (*)(void*))>(demoInstance::someFunc);
How can I call this function with a class' member function as parameter so that this one can use it as callback?
Any idea or remark is appreciated. Thanks and regards tobias
The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .
the constructor is the first function which get called. and we can access the this pointer via constructor for the first time. if we are able to get the this pointer before constructor call (may be via malloc which will not call constructor at all), we can call member function even before constructor call.
Yes, it can. This is purpose of casting function pointers, just like usual pointers. We can cast a function pointer to another function pointer type but cannot call a function using casted pointer if the function pointer is not compatible with the function to be called.
Passing Pointers to Functions in C++ C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.
You can't call the member function directly. Member function pointers are not the same type as function pointers.
You'll need to wrap it in a compatible function somehow. However, if your outer function (the one taking the function pointer as an argument) is not re-entrant and does not supply an extra argument for use by the function pointer, you won't be able to pass the instance upon which the member function operates, so you won't actually be able to make the call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With