关于函数指针的用法:
Testapp.c 里面有这样的一个结构体
struct testcase testcases[] = {
{ "cache_create", cache_create_test },
{ "cache_constructor", cache_constructor_test },
{ "cache_constructor_fail", cache_fail_constructor_test },
..........................此处省略一大部分类似的结构.......................
{ "binary_pipeline_hickup", test_binary_pipeline_hickup },
{ "shutdown", shutdown_memcached_server },
{ "stop_server", stop_memcached_server },
{ NULL, NULL }
};
struct testcase 是这样一个结构体
struct testcase {
const char *description;
TEST_FUNC function;
};
里面声明的函数类型TEST_FUNC 是经过typedef重新定义的一个函数指针
typedef enum test_return (*TEST_FUNC)(void);
而枚举类型 enum test_return 被定义为
enum test_return {TEST_SKIP, TEST_PASS, TEST_FAIL};
function定义为这样的结构
static enum test_return cache_create_test(void)
{
cache_t *cache = cache_create("test", sizeof(uint32_t), sizeof(char*),
NULL, NULL);
assert(cache != NULL);
cache_destroy(cache);
return TEST_PASS;
}
函数里面具体做些什么就不去探究了
看到结构体数组 testcases的最后一个值为{NULL, NULL},因此可以用该条件判断循环结束,来遍历数组
for(ii=0; testcases[ii].description!=NULL; ++ii)
{
printf("description:%s",testcases[ii].description);
//执行函数
testcases[ii].function();
}
这样就能将所有的函数都去执行一次
本文详细介绍了函数指针的用法,并通过一个具体的结构体数组展示了如何使用函数指针遍历一系列测试用例,每个测试用例对应一个特定的功能函数。

被折叠的 条评论
为什么被折叠?



