Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast pointer to member function to normal pointer

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

like image 907
Atmocreations Avatar asked Nov 18 '10 01:11

Atmocreations


People also ask

How do you get a pointer to member function?

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 .

Can we call member function using this pointer from constructor?

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.

Can you cast function pointers?

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.

How do you pass this pointer to a function in C++?

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.


1 Answers

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.

like image 84
Jonathan Grynspan Avatar answered Sep 20 '22 08:09

Jonathan Grynspan