Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 912
Farah Avatar asked Dec 06 '25 05:12

Farah


2 Answers

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,...);
like image 169
fredoverflow Avatar answered Dec 07 '25 22:12

fredoverflow


In this example, MyCallback describes the pointer to function which has the following signature: it returns void and has the arguments of specified types (i.e. (MyHandle handle, void* context, MyResult result, ... ))

In the MyMethod, the argument of the type MyCallback is given, that means that the corresponding function can then be called as:

(*cb)(handle, context, result, ...)

(handle, context, result, etc should be defined somewhere and have the types corresponding to the argument types provided for MyCallback)

like image 22
Ashalynd Avatar answered Dec 07 '25 20:12

Ashalynd