typedef void (*MyCallback) : What is it and how to use it?

c++, pointers, typedef, void

Solution

This particular `typedef` introduces a type alias named `MyCallback` for the type "pointer to function taking a handle, a context and a result and returning void". If you have a function taking `MyCallback` as a parameter, you can pass a pointer to a concrete callback as an argument:

void someFunction(MyCallback callback);
void someCallback(MyHandle handle, void* context, MyResult result, ...);

someFunction(&someCallback);
someFunction( someCallback);   // the & is optional

Note that this will only work if `someCallback` is a top-level function or a static member function. Non-static member functions (aka methods) are completely different beasts.

In case you are simply confused by the C declarator syntax, C++11 allows the following alternative:

using MyCallback = void (*)(MyHandle handle, void* context, MyResult result,...);

Problem

I'm a Java developer. I'm trying to understand a C/C++ project, and I find in it this : `*.h` file : ``` typedef void (*MyCallback) (MyHandle handle, void* context, MyResult result, ... ); int MyMethod(MyHandle handle, void* context, MyCallback cb); ``` `*.cpp` file: ``` int MyMethod(MyHandle handle, void* context, MyCallback cb){ //... } ``` And I truly didn't get what it is about... Can anybody explain to me what is that "`typedef void`" for? I'm used only to simple typedef for simple structures... But in this one I can see a scary pointer (sorry pointers phobia for a Java developer...). Moreover, why did we do that typedef?? I don't see it any pointer on `MyCallBack` in `MyMethod` function. I need to understand then the meaning of this code. Thank you a lot!

Original source

Related problems