Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the parameter void(*pfn)(void*)?

I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

like image 773
dikidera Avatar asked Jun 01 '11 21:06

dikidera


2 Answers

It's a function pointer to a function returning void and accepting void *.

void example(void *arg);

You can find more information about function pointers in C++ (and in C) at The Function Pointer Tutorials.

like image 174
cnicutar Avatar answered Oct 10 '22 04:10

cnicutar


This is a function pointer (or a pointer to a function).

void(*pfn)(void*)

This is broken down as such:

*pfn (the name of the pointer i.e. pointer to a function)

(void *) (these are the parameters to the function ie. a simple pointer to anything)

void (this is return from the function)

So if you have a function like this:

void DoSomeThing(void *data) {
  ... does something....
}

then you can pass it into the CreateThread function like so...

int i  = 99;
void * arg = (void*)&i;
pthread_t thread = CreateThread(DoSomeThing, arg, ... other parameters ...);

So somewhere in CreateThread it will make a call:

pfn(parg);

and your function DoSomeThing will be called and void * data you get will be the arg you passed in.

More info:

Remember that code is just a sequence of bytes in memory. It's just how the cpu interprets them that makes them different from the thing we call data.

So at any point in a program we can refer to another part of the code by it's memory address. Since the code is broken down into functions with in C, this is a useful unit of reuse that C understands and allows us to treat the address of the function as just another pointer to some data.

In the above example the CreateThread function needs the address of a function so it can execute that function in a new thread. So we pass it a pointer to that function. Hence we pass it a function pointer.

like image 37
Preet Sangha Avatar answered Oct 10 '22 03:10

Preet Sangha