void* 函数指针数组转换
void* function pointer array cast
我有一个如下所示的数组:
void* functions[]; // pointer to functions, each function returns an int and has int parameters A and B
我想将其转换为以下内容:
int (*F)(int a, int b) = ((CAST HERE) functions)[0];
int result = F(a, b);
我已经尝试将“(int (*)(int, int))”作为转换,但编译器抱怨我正在尝试将函数指针用作数组。
对函数类型使用 typedef 会有所帮助:
typedef int F_type(int, int);
那你可以这样写:
F_type *F = (F_type *)(functions[0]);
在使用索引运算符之前尝试将 functions
转换为其他内容将是未定义的行为(严格的别名违规)。
请注意,标准 C 不支持将 void *
转换为函数指针。如果可能的话,让数组首先成为函数指针:
F_type *functions[] = { &func1, &func2 };
注意。有些人更喜欢对函数指针类型使用 typedef,而不是函数类型。我认为避免指针 typedef 的代码更具可读性,但我提到这一点是为了让您理解其他建议。
function
是指向 void
类型数据的指针数组。您希望将其转换为指向类型 int (*)(int, int)
的指针的指针,即 int (**)(int, int)
,因此以下工作:
int (*F)(int, int) = ((int (**)(int, int)) functions)[0];
正如 , the above will result in undefined behaviour. You might want to read this post and this 指出的那样。
理想情况下,您会这样做:
// Array of 2 pointers to functions that return int and takes 2 ints
int (*functions[2])(int, int) = {&foo, &bar};
// a pointer to function
int (*F)(int, int) = functions[0];
int r = F(3, 4);
使用 (int (**)(int, int))
进行转换现在似乎可以解决问题,但它会调用 未定义的行为!
将 void*
转换为函数指针不是标准 C。
请注意,别名 void*
为不同的类型;严格的混叠违规。在 What is the effect of casting a function pointer void?
中阅读更多内容
请考虑从一开始就使用函数指针数组。
我有一个如下所示的数组:
void* functions[]; // pointer to functions, each function returns an int and has int parameters A and B
我想将其转换为以下内容:
int (*F)(int a, int b) = ((CAST HERE) functions)[0];
int result = F(a, b);
我已经尝试将“(int (*)(int, int))”作为转换,但编译器抱怨我正在尝试将函数指针用作数组。
对函数类型使用 typedef 会有所帮助:
typedef int F_type(int, int);
那你可以这样写:
F_type *F = (F_type *)(functions[0]);
在使用索引运算符之前尝试将 functions
转换为其他内容将是未定义的行为(严格的别名违规)。
请注意,标准 C 不支持将 void *
转换为函数指针。如果可能的话,让数组首先成为函数指针:
F_type *functions[] = { &func1, &func2 };
注意。有些人更喜欢对函数指针类型使用 typedef,而不是函数类型。我认为避免指针 typedef 的代码更具可读性,但我提到这一点是为了让您理解其他建议。
function
是指向 void
类型数据的指针数组。您希望将其转换为指向类型 int (*)(int, int)
的指针的指针,即 int (**)(int, int)
,因此以下工作:
int (*F)(int, int) = ((int (**)(int, int)) functions)[0];
正如
理想情况下,您会这样做:
// Array of 2 pointers to functions that return int and takes 2 ints
int (*functions[2])(int, int) = {&foo, &bar};
// a pointer to function
int (*F)(int, int) = functions[0];
int r = F(3, 4);
使用 (int (**)(int, int))
进行转换现在似乎可以解决问题,但它会调用 未定义的行为!
将 void*
转换为函数指针不是标准 C。
请注意,别名 void*
为不同的类型;严格的混叠违规。在 What is the effect of casting a function pointer void?
请考虑从一开始就使用函数指针数组。