Home > Enterprise >  Function Pointers, In STM32 and how do i understand these Type Handles?
Function Pointers, In STM32 and how do i understand these Type Handles?

Time:03-02

I'm getting a very confusing error as I may be making a small mistake with the phrasing or the type handles or it could be a more complicated problem

Basically I want to create this funciton Buf_IO(HAL_StatusTypeDef IO) that can take one of two inputs either HAL_SPI_Transmit or HAL_SPI_Recieve

these are both defined as

HAL_StatusTypeDef HAL_SPI_Transmit/*or Recieve*/(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)

so in my code i have defined my function pointer as follows

HAL_StatusTypeDef (FuncPtr*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t) = IO;

where IO is the argument to my function however for some reason i get the error

invalid conversion from 'HAL_StatusTypeDef (*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t)' {aka 'HAL_StatusTypeDef (*)(__SPI_HandleTypeDef*, unsigned char*, short unsigned int, long unsigned int)'} to 'void (*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t)' {aka 'void (*)(__SPI_HandleTypeDef*, unsigned char*, short unsigned int, long unsigned int)'}

for clarity this is how i have declared the funtion in the .cpp file

void MAX_Interface::Buf_IO(HAL_StatusTypeDef IO)
{
    HAL_StatusTypeDef (FuncPtr*)(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t) = IO;
    uint8_t* buf_ptr = (uint8_t*) &OBuf;

    HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_RESET);
    FuncPtr(h_SPI, buf_ptr, 3, 100);
    HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_SET);
}

I do understand that i may be overcomplicating this as I have previously written just two different functions for transmitting an receiving but I'm looking to make my code more concise and also learn a bit in the process so feel free to suggest a more elegant solution if you can think of one?

CodePudding user response:

In C , you should use the using directive to define the function signature. using is similar to typedef in C, but makes things much more readable.

using IO = HAL_StatusTypeDef(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t);

Note, that IO is now the alias of the function signature itself, not a pointer to the function.

Now, in your function you use it as IO* to specify that the parameter is a function pointer:

void MAX_Interface::Buf_IO(IO* funcPtr)
{
    uint8_t* buf_ptr = (uint8_t*) &OBuf;

    HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_RESET);
    funcPtr(h_SPI, buf_ptr, 3, 100);
    HAL_GPIO_WritePin(GPIOB, h_CS, GPIO_PIN_SET);
}
  • Related