Point a member function pointer to a regular pointer

I currently have a class of this kind abbreviated for simplicity:

class MyClass {
    public: 
        MyClass();
        void* someFunc(void* param);
}

Now I need to call a function of this type (which is not a member of any class and which, unfortunately, cannot change ), but which I need to call in any case:

void secondFunc(int a, int b, void *(*pCallback)(void*));

Now I need to pass the address of someFunc instance.

The sample does not work:

MyClass demoInstance;
// some other calls
secondFunc( 1, 2, demoInstance::someFunc() );

I also tried using roles such as:

(void* (*)(void*)) demoInstance::someFunc;
reinterpret_cast<(void* (*)(void*))>(demoInstance::someFunc);

How can I call this function using a member function of a class as a parameter so that it can be used as a callback?

Any idea or comment appreciated. Thank you and welcome Tobias

+3
source share
6 answers

C- - ++ , C cdecl, - ( !).

, , secondFunc() - ( this). , - . , . . , MT, Thread Local Storage (TLS),

SomeFunc -type, .

+5

-. - , .

- . , (, ), , , , .

+8

. ++ , . , , C, . -. .

+1
class MyClass 
{
public: 
    MyClass();
    void* someFunc(void* param);
};

void* callback(void*)
{
    MyClass instance;
    instance.someFunc(0 /* or whatever */);
}

void foo()
{
    secondFunc( 1, 2, callback);
}
0

, .

- :

struct MyData {
   MyStruct  *myInstance;
   (void *)(MyStruct::myFunction)(void *data);
   void * dataPointer ;
}

Create a function that can call the correct method:

void *proxyFunc( MyData *data)
{
  return (data->myInstance->*(data->myFunction))(data->dataPointer);
}

Then call function 2 as:

MyData  dataP = { someInstance, &MyStruct::someFunc, &dataPtr };
secondFunc(proxyFunc, &dataP);
0
source

See this sample:

#include <iostream>

class MyClass 
{
public: 
    MyClass()
    {
    }

    void* someFunc(void* param)
    {
        std::cout << "someFunc" << std::endl;
        return (void*)0;
    }
};

typedef void* (MyClass::*MemFun)(void*);

void secondFunc(int a, int b, MemFun fn)
{
    MyClass* ptr = 0;
    // This is dangerous! If the function someFunc do not operate the data in the class.
    // You can do this.
    (ptr->*fn)(0);
    std::cout << "Call me successfully!" << std::endl;
}

int main()
{
    secondFunc(1, 2, &MyClass::someFunc);

    system("pause");

    return 0;
}
0
source

Source: https://habr.com/ru/post/1775532/


All Articles