我正在为我的项目编写一些测试,这些函数具有相同的返回类型但参数数量不同。我想使用函数指针数组来调用这些测试函数。如何为此类函数声明函数指针数组?
函数声明为:
bool test1();
bool test2(char const *string, uint32_t length);
最佳答案
考虑到函数指针不是魔术,它们仍然必须遵守 ABI 调用约定,这意味着具有特定签名的函数与具有不同签名的函数本质上是不同的。
使用函数指针更多的是一种拥有动态方法的方式,而不是实现多态性。编辑:这不是多态性。
但是,您可以通过替换每个测试函数以接受 void*
来完成您所要求的一些任务,然后将参数编码到结构中。
// Declare the test functions
//bool test1();
bool test1(void* struct_address)
{
// struct address unused.
}
// Parameters for test2
struct test2{
char const* string;
uint32_t* length;
}
//bool test2(char const *string, uint32_t length);
bool test2(void* struct_address)
{
struct test2 test2_s = *(struct test2*)(struct_address);
// Work with test2_s
}
// Declare the function pointer
bool (*test_ptr)(void *);
// call test1
test_ptr = test1; test_ptr((void*)NULL);
// call test2
struct test2 test2_s = {param1,param2};
test_ptr = test2; test_ptr((void*)&test2_s);
要小心,因为如果传递错误的结构类型,您将遇到内存泄漏和段错误。不过,由于这是一个测试环境,因此可以缓解这种情况。
关于arrays - 如何为具有不同参数的函数声明函数指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71942183/