Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's void *userData exactly?

Tags:

c

In a C function declaration, I have seen this parameter definition:

void *userData

so, what exactly is that? My guess: the void says it can be anything arbitrary, or even nothing. Almost similar to id of objective-c. It just allows to pass in whatever data structure you like.

The star in front of userData says, that the argument must be passed in by reference.

So when using this stuff in the function body, typically it must be casted and dereferenced. So if I pass in an pointer to SomeClass instance, I would get that like this:

SomeClass *myObj = (SomeClass*)userData;

In the case I had nothing special to pass along, I would provide NULL as argument.

Are my assumptions correct? Or did I get something wrong?

like image 911
dontWatchMyProfile Avatar asked Mar 22 '26 14:03

dontWatchMyProfile


1 Answers

A void * is a pointer to a structure of unknown type. You can think of it as "a pointer to anything". It's not the same as Objective-C's id type, which is the type of any object. An id looks like this:

typedef struct objc_object {
  Class isa;
} *id;

Typically in Objective-C (and I'm sure in C too) a framework might use some callback to tell you something. That callback will often take a parameter containing data that you give it - perhaps the object that started the action, and that needs to know that something's happened. A void * parameter lets the framework define a callback without depending on your code, so you can put anything you like into the callback. (Of course that means you also have to ensure that you cast your void *userData back into the appropriate type.)

like image 144
Frank Shearar Avatar answered Mar 25 '26 08:03

Frank Shearar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!