C void* 函数指针参数

标签 c function-pointers

我正在尝试在 ARM 中创建一个任务队列。基本思想如下。

typedef void (*funcpointer)(void *);     // the argument being passed will be a void pointer that I can hopefully typecast

struct sQueue{
   funcpointer       func_address;        // this stores the address of the function to be called
   void              *func_parameter;                   // this stores the address of the struct that is passed to the function
   uint32_t          TimeStamp;                  // the time at which the function should be called     
};

sQueue Func_List[10];

计划是能把应该调用的函数的地址放到Func_List[x].func_address中。

我希望能够将接受指向不同结构类型的指针的函数的地址放在 func_address 中。 这是一个例子:

void Config_ADC(sADC_Settings *pSettings);

void Enable_RX(sRX_Top_Settings *pSettings);

这两个函数都有效地接受一个指向结构的 32 位指针,但在这些情况下,结构的类型不同。

当我尝试分配 Func_List[x].func_address = Config_ADC 时,编译器会提示:

不能将“void (*)(sADC_Settings *)”类型的值分配给“funcpointer”类型的实体

关于如何实现此目标的任何想法?我当然可以更改函数 Config_ADC 以接受 void* 指针,然后在函数内部对其进行类型转换,但我真的不想那样做。

最佳答案

IIRC 通过具有不同签名的函数指针调用函数是 UB。

每个不匹配的函数类型都需要一个代理函数。

void Config_ADC(sADC_Settings *pSettings);
void Config_ADC_proxy(void *pSettings){
  Config_ADC((sADC_Settings*) pSettings);
}

关于C void* 函数指针参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32437069/

相关文章:

c++ - 声明类型为 void C++ 的函数数组

javascript - 在 JavaScript 中使用函数指针

c# - 如何在 C# 中实现 C++ 风格的函数指针?,不使用委托(delegate)

c - 警告 : passing 'const char *' to parameter of type 'char *' discards qualifiers

无法将数据写入结构

python - 指针和 "Storing unsafe C derivative of temporary Python reference"

c++ - 在C++中定义带有函数参数的结构体方法

c - 我应该为 FreeRTOS 系统上的程序选择什么调度?

php - C 中 PHP 的 stripslashes() 的等价物?

c - 如何知道一个函数是否在 C 中被调用,是否使用 gdb 或任何其他工具进行类型转换?