cancel
Showing results for 
Search instead for 
Did you mean: 

Is there a way to provide context pointer to HAL callback functions

MCamp.1
Associate

I'm new to ST and am evaluating if the STM32G0 family is a good fit for us. The idea of using the HAL driver interface is appealing as it would allow migration to other chips in the larger STM32 family without code changes.

I'm working on making a little I2C client example using the interrupt interface. In other vendor drivers for this sort of stuff, you can often supply a context pointer to these callbacks to inject user data without the need for hard coding access to global scoped symbols. Am I just missing how to do this with the HAL, or are global symbols the only way? If it is, it will make writing abstrated and testable code a lot more boilerplaty and challenging.

4 REPLIES 4
Pavel A.
Evangelist II

The callbacks receive the peripheral's "handle" pointer as argument (see for example here)

You can define the handles in a containing structure; add your custom fields before or after the HAL structure.

--pa

Not sure what the correct technical term here is, perhaps overloading.

Create a structure whose first member is the structure/instance you'd normally pass by address, add in all the stuff you want held on a per-instance basis after that, and then cast this back to your super-structure as needed to access you own content.

Tips, buy me a coffee, or three.. PayPal Venmo Up vote any posts that you find helpful, it shows what's working..
MCamp.1
Associate

Thanks for the info. I'm not sure the name either, but I've seen that pattern used all over the Linux kernel in device drivers. This could work, but I don't see how it would integrate well with the code generated by STMCubeMX since it defines the instance of the driver handle in the generated code. I can't think of a good way to do the nested struct trick in a way that wouldn't get stomped by CubeMX. I could also see making a system where I can call a function with a handle that returns a context pointer. I was really hoping for something in the HAL that enable this, but it looks like I'm not missing anything.

BMere.1
Associate

Struct overloading can't work because of the code generator.