2

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!

Farah
  • 2,469
  • 5
  • 31
  • 52
  • See this answer: http://stackoverflow.com/questions/3982470/what-does-typedef-void-something-mean?lq=1 – Howie Feb 27 '14 at 13:32

3 Answers3

11

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,...);
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
2

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)

Ashalynd
  • 12,363
  • 2
  • 34
  • 37
2

That's a function pointer typedef.

In Java, you often have an interface with a RunThis() function or something, and then pass around subclass objects.

In C and C++, this isn't necessary. Instead, you can just pass a pointer to the function.

This is very useful, especially in C where you need a way to specify e.g. how to compare different types of objects in generic code, but don't have classes. It's also useful in multithreading to say what code the new thread should execute (see pthreads and std::thread).

Robert Mason
  • 3,949
  • 3
  • 31
  • 44