I would like to use the p_context
member of the uart_callback_args_t*
that the SCI UART HAL passes into my callback function.
A similar question from 2 years ago says "don't do that" without a satisfactory explanation, so I dug deeper into the SSP HAL code. p_context
(at least for the SCI UART) definitely does not point to the function that was executing at the time the callback happened; it gets assigned from p_ctrl->p_context
just before the callback function is called. Using the debugger, I can verify that p_context
points to g_uart0
.
The Syngery-generated code declares a const const uart_cfg_t g_uart0_cfg
where .p_callback = user_uart0_callback
and .p_context = &g_uart0
. g_uart0
is a const uart_instance_t
that points back to g_uart0_ctr
l and g_uart0_cfg
. (Most members of structs are omitted because they are irrelevant to this question.)
R_SCI_UartOpen
copies the callback pointer from p_cfg
(which is const) to p_ctrl
(which is mutable)
p_ctrl->p_callback = p_cfg->p_callback;
r_sci_uart_rxi_isr
has this sequence for the callback function, once it checks that p_callback
is non-NULL
uart_callback_args_t args;
args.channel = channel;
args.data = 0U;
args.p_context = p_ctrl->p_context;
args.event = UART_EVENT_RX_COMPLETE;
p_ctrl->p_callback(&args);
Note that, per the initialization of g_uart0_cfg
, p_ctrl->p_context = &g_uart0
. I can't find any code where p_context
is actually dereferenced; it only seems to get copied into a p_context
of another struct that is passed to another function.
Further, the documentation for sci_uart_instance_ctrl_t.p_context
says "Pointer to user interrupt context data," (r_sci_uart.h, line 92) which strongly implies that the user can use this pointer to pass context into the callback function.
So, can I use p_context
for any pointer I want to, and if so, is it better to set it once in p_cfg
(maybe making a non-const copy and replacing the value) or can I safely change it in p_ctrl
after the call to R_SCI_UartOpen
?
Also, information about my environment:
Board: S5D9 PK
Device: R7FS5D97E3A01CFC
Toolchain: GCC ARM Embedded
Toolchain Version: 4.9.3.20150529
SSP Version: 1.5.0-rc.1