Reputation: 21019
I have the following typedef
function prototype:
typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
I have no idea how to use it. I understand that (int, siginfo_t *, void*)
is typedef
-ed into sa_sigaction_t
. But how would I use it? These are all return types with no variable names specified.
So I assume I want to create a variable: sa_sigaction_t handler
. How would I use it? The syntax is quite confusing.
Thanks,
Upvotes: 1
Views: 890
Reputation: 24447
The typedef
in this case is sort of a short hand for a function which returns void
and takes 3 arguments (int
, siginfo_t *
and void *
). This is mainly useful for if you want to pass a function around as a callback for example.
void func1(sa_sigaction_t handler)
{
handler(...);
}
func1
invokes any function of type sa_sigaction_t
. You can call it like so:
void func2(int a, siginfo_t * b, void * c)
{
...
}
int main(void)
{
func1(func2);
/*
* Equivalent to:
* sa_sigaction_t handler = func2;
* func1(func2);
*/
return 0;
}
On the other hand, if you did not have the typedef
, your code would be more verbose:
void func1(void(*handler)(int, siginfo_t *, void*))
{
handler(...);
}
void func2(int a, siginfo_t * b, void * c)
{
...
}
int main(void)
{
func1(func2);
/*
* Equivalent to:
* void(*handler)(int, siginfo_t *, void*) = func2;
* func1(func2);
*/
return 0;
}
Something to note is that sometimes you will see func2
and other times &func2
, but these are both the same thing.
Upvotes: 1
Reputation: 258568
I understand that (int, siginfo_t , void) is typedef-ed into sa_sigaction_t.
Actually no. sa_sigaction_t
is a pointer to a function that returns void
and takes (int, siginfo_t *, void *)
as parameters.
So if you have:
void foo(int, siginfo_t*, void*)
{
}
you can do:
sa_sigaction_t fooPtr = &foo;
and then call it like this:
fooPtr(0,NULL,NULL);
Upvotes: 1
Reputation: 16718
If you have a function pointer declared:
sa_sigaction_t handler;
You can call it like:
handler( ... );
The clue is in the brackets, really. void (*sa_sigaction_t)
is different from void *sa_sigaction_t
.
Upvotes: 0