arrays - 如何为具有不同参数的函数声明函数指针数组?

标签 arrays c function unit-testing function-pointers

我正在为我的项目编写一些测试,这些函数具有相同的返回类型但参数数量不同。我想使用函数指针数组来调用这些测试函数。如何为此类函数声明函数指针数组?

函数声明为:

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/

相关文章:

python - 效率与可读性 : obfuscation when using nested boolean index arrays

arrays - 填充 UITableViewController

c - 从c中的二进制文件中读取double

javascript - 如何编写代码以在执行 showpic 函数时动态创建带有图像名称的 <span 元素?

c - 在 C 中调用和执行函数的最快方法是什么?

c++ - 如何通过函数参数返回动态数组?

sql - 将 postgresql 数组解包成行

通过niceness改变所有进程的niceness

c - 在旧的原始套接字教程中使用 ntop() 而不是 ntoa()

php - Stripe.js/stripe.php - 所有卡错误都有效(过期、cvc、不正确的#),卡被拒绝除外