1

In my application I use a method of a C++ - API that is defined like this:

ApiDataType_::specialApiMethod(ApiInterface *pVar, void* pV)

So as first parameter I need a parameter of typeApiInterface.

If I declare a static method testFunc() in my program, I can use this method as first parameter in specialApiMethod().

//.h
public:
   static void testFunc(ApiDataType adt, void* ptr);

//.cpp
{    
myClassObj->specialApiMethod(MyClass::testFunc, this)
}

This only works if testFunc() is static. Without the static keyword, it will not work. Why this works with the static keyword?

taathy
  • 155
  • 1
  • 1
  • 9
  • 2
    Because member functions take `this` as implicit first argument, so w/o static `testFunc`'s the signature would be sth like `void testFunc(MyClass*, ApiDataType, void*)`. In case of static it is just a freestanding function. – alagner Jul 08 '22 at 07:23
  • 1
    static methods does not need an instance of an object to be called. If a function is `without the static keyword` then it is a method which is called on an instance of its class – marcinj Jul 08 '22 at 07:23
  • 1
    There's no "there" there for that callback function. non-static member functions are provided an implicit `this`. That doesn't come out of thin-air. Static member function don't get, nor need, such a thing. You can still make this work by having your `testFunc` resolve it's `void *ptr` (which you're providing a `this` for), and using that to fire a non-static member (that you also write) passing only the `adt` arg. – WhozCraig Jul 08 '22 at 07:25
  • 1
    Using Visual C++? It will ignore the missing `&` before `MyClass::testFunc`, but other compilers correctly insist that you write `&MyClass::testFunc`. – MSalters Jul 08 '22 at 07:27
  • Does this answer your question? [Using a C++ class member function as a C callback function](https://stackoverflow.com/questions/1000663/using-a-c-class-member-function-as-a-c-callback-function) – JaMiT Jul 08 '22 at 09:16
  • @MSalters: The `&` isn’t required for the static case. – Davis Herring Jul 08 '22 at 20:30

0 Answers0