2

I am trying to use callback registers in STM32. I am writing most of the interfaces in C++ in hope of being completely independent of HAL one day, but I am kind of using it currently to make development faster.

I am working on defining a UART class and to call that for every UART peripheral I define. Now I have CallBacks enabled, and I do believe that I can define a call back functions and pass it as a pointer for example. The Rx CallBack is defined as follows

  void (* RxCpltCallback)(struct __UART_HandleTypeDef *huart);            /*!< UART Rx Complete Callback             */

And here is the call for that callback when the Rx buffer is full

#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) /*Call registered Rx Half complete callback*/
huart->RxCpltCallback(huart);

In my class I plan to have a CallBack function and pass its pointer to this function in my initialization.

But sadly it doesn't know how to convert a member function of a class to a function.

Here is my code inside the constructor for that part

uartx.RxCpltCallback=rx_cplt_callback;

Here is my code for the callback function inside my class

void uart::rx_cplt_callback(__UART_HandleTypeDef* uart_)

Here is the error code it is giving me when trying to compile.

cannot convert 'uart::rx_cplt_callback' from type 'void (uart::)(__UART_HandleTypeDef*)' to type 'void (*)(__UART_HandleTypeDef*)'
   26 |     uartx.RxCpltCallback=rx_cplt_callback;

I honestly don't know how to solve this problem while not writing code outside of the class. Yes for sure I could write function out of the class that directs me to this function but that would defeat the purpose.

Thank you very much.

Regards Riyad

  • 1
    It doesn't know how to convert a non-static member function of a class to "a function", because a member function doesn't behave like a (non-member) function. Two distinct bits of information are needed to call a member function - a pointer to the member and an object for it to act on. A call of `object.member()` (or `pointer->member()`) needs BOTH `object` and `member` to be specified. You will need to provide a callback that is a "normal" function and pass both pieces of information it needs (e.g. wrap a pointer to an object and a pointer to member in a struct, and pass the address of that). – Peter Feb 07 '21 at 06:31
  • Try this: uart c; uartx.RxCpltCallback= = std::bind(&uart::rx_cplt_callback, &c, _1) ; – OLNG Feb 07 '21 at 06:40
  • @OLNG `std::bind` can't be converted to a function pointer https://stackoverflow.com/questions/13238050/convert-stdbind-to-function-pointer – Alan Birtles Feb 07 '21 at 06:51
  • I guess we have to either use a function which calls it, or use lambda; void (struct __UART_HandleTypeDef *huart){static uart c; c.rx_cplt_callback(huart);} or use lambda to call (may have to use a global variable of uart) – OLNG Feb 07 '21 at 07:23

0 Answers0