1

I have assigned a function to an variable

p_samplen_->onData = onData;

PVOID onData(PVOID args) {

}

and it worked.

I tried to assign this variable to a function in class but it did not work.

p_samplen_->onData = &MyClass::onData;

PVOID MyClass::onData(PVOID args) {

}

the error is

test.cpp:32:48: error: assigning to 'startRoutine' (aka 'void *(*)(void *)') from incompatible type 'void *(MyClass::*)(void *)'

Please help me on this.

abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • Likely a duplicate of https://stackoverflow.com/questions/2402579/function-pointer-to-member-function. You should consider `std::function` instead – Tas Apr 29 '20 at 04:52
  • The error message tells you: they are incompatible types. `MyClass::onData` needs a `MyClass` as well as an `int` to be called – Caleth Apr 29 '20 at 08:03

1 Answers1

2

Your syntax might be incorrect. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:

#include <iostream>

class MyClass 
{
public:
    void *f(void *);
    void *(MyClass::*x)(void *); // <- declare by saying what class it is a pointer to
};

void *MyClass::f(void *ptr) 
{
    return ptr;
}


int main() 
{
    MyClass a;
    a.x = &MyClass::f; // use the :: syntax
    int b = 100;
    std::cout << *(int *)((a.*(a.x)) (&b)) << std::endl;
    return 0;
}

OR

You can use functional and bind in C++.

Example:

#include <iostream>

#include <functional>

class MyClass 
{
public:
    void *f(void *);
    std::function<void *(void *)> function;
};

void *MyClass::f(void *ptr) 
{
    return ptr;
}


int main() 
{
    int b = 100;

    MyClass a;
    a.function = std::bind(&MyClass::f, &a, &b);
    std::cout << *(int *)a.function(&b) << std::endl;
    return 0;
}
abhiarora
  • 9,743
  • 5
  • 32
  • 57