Reputation: 20196
I am using xTaskCreate in FreeRTOS whose 4th parameter (void * const) is the parameter to pass to the function invoked by the new Thread.
void __connect_to_foo(void * const task_params) {
void (*on_connected)(void);
on_connected = (void) (*task_params);
on_connected();
}
void connect_to_foo(void (*on_connected)(void)) {
// Start thread
xTaskCreate(
&__connect_to_foo,
"ConnectTask",
STACK_SIZE,
(void*) on_connected, // params
TASK_PRIORITY,
NULL // Handle to the created Task - we don't need it.
);
}
I need to be able to pass in a function pointer with signature
void bar();
But I can't work out how to cast void* to a function pointer that I can invoke. Closest I can get is:
error: 'void*' is not a pointer-to-object type on line 3
How can I cast task_params to a function pointer that I can invoke?
NB the code above is grossly simplified.
Upvotes: 1
Views: 3392
Reputation: 180303
There's an portable alternative to a direct cast. A pointer to a function pointer is itself a data pointer. That is to say, given auto connect_to_foo_ptr = &__connect_to_foo
, void* ptr = &connect_to_foo_ptr
is legal everywhere.
Of course, to call it, you'll need to cast the void*
back to a void (**)(void * const task_params)
, and dereference it twice. The first dereference gets you back the function pointer, the second gets you the original function.
One restriction here is that you need to assure that connect_to_foo_ptr
doesn't go out of scope, but that's usually not a problem. You can usually make it static
, but even that is not needed for the common callback pattern.
Upvotes: 2
Reputation: 52621
Something along these lines:
typedef void (*OnConnected_t)();
OnConnected_t on_connected = OnConnected_t(task_params);
on_connected();
Upvotes: 9