我正在尝试创建一些我可以用来创建自己的单元测试库的宏.我的头文件如下所示:
#ifndef _TEST_H_
#define _TEST_H_
#include <stdio.h>
#include "hehe_stack.h"
static hehe_stack* tests;
typedef int (*testfunc)();
#define test_init() tests = hehe_stack_init();
#define test_register(test) hehe_stack_push(tests, test);
#define test_info() fprintf(stdout, "running %s :: %s \n", __FILE__, __func__);
#define test_run() testfunc = (int (*)()) hehe_stack_pop(tests); testfunc(); return 0;
#endif
Run Code Online (Sandbox Code Playgroud)
在每个测试.c文件中,我想将一些函数指针推入测试堆栈,然后将每个函数指针弹出堆栈并调用它.我的堆栈pop方法返回一个void指针,我推送到它的函数指针返回一个int并且不带参数.我的语法不正确吗?我觉得我应该能够做到这一点.
假设所有函数共享相同的返回类型,通过"泛型"函数指针调用每个函数是否有效,该指针是用空括号声明的(因此它不指定其参数)?
这是一个示例代码,说明了它:
#include <stdio.h>
void fun1(void)
{
printf("fun1\n");
}
void fun2(int a)
{
printf("fun2: %d\n", a);
}
void fun3(int a, int b)
{
printf("fun3: %d %d\n", a, b);
}
int main(void)
{
void (*pf)(); // pseudo-generic function pointer
pf = fun1;
pf();
pf = fun2;
pf(0);
pf = fun3;
pf(1, 2);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 可以使用泛型存储正常指针void*.例如
void* arr[10];
arr[0] = pChar;
arr[1] = pINt;
arr[2] = pA;
Run Code Online (Sandbox Code Playgroud)
不久之后,我遇到了一个讨论,void*可能无法在所有平台(例如64位或更多)中存储没有数据丢失的函数指针.我不确定这个事实.
如果这是真的,那么存储函数指针集合的最便携方式是什么?[注意:这个问题没有令人满意地回答这个问题.]
编辑:我将使用索引存储此函数指针.每当访问此集合时,都会对每个索引进行类型转换.截至目前,我感兴趣的只是制作阵列或vector它.