ç投无效指针函数指针 [英] C cast void pointer to function pointer

查看:173
本文介绍了ç投无效指针函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创造一些宏,我可以用它来创建自己的单元测试库。我的头文件是这样的:

I am trying to create some macros that I can use to create my own unit testing library. My header file looks like this:

#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

在每个测试.c文件我想推一些函数指针进入测试栈,然后弹出每个函数指针出栈并调用它。我的出栈方法返回一个空指针,那我推到它返回一个int和不带任何参数的函数指针。是我的语法不正确的?我觉得我应该能够做到这一点。

In each test .c file I want to push a number of function pointers into the tests stack and then pop each function pointer out of the stack and call it. My stack pop method returns a void pointer, and the function pointer that I am pushing onto it returns an int and takes no parameters. Is my syntax incorrect? I feel like I should be able to do this.

推荐答案

C99标准不允许指针之间转换数据(标准,对象或不完全类型,例如的char * 无效* )和函数指针。

The C99 standard does not allow to convert between pointers to data (in the standard, "objects or incomplete types" e.g. char* or void*) and pointers to functions.

6.3.2.3:8的指针一种类型的功能可以被转换为一个指针到另一种类型的,然后再返回的函数;结果应
  比较等于原始指针。如果转换后的指针用于
  以呼叫类型与所指向的兼容功能
  类型,行为是不确定的。

6.3.2.3:8 A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

的一个原因是对象指针和指向函数不必是相同的大小。上的示例体系结构,前者可以是64位的,而后者的32位

One reason is that pointers to objects and pointers to functions do not have to be the same size. On an example architecture, the former can be 64-bit and the latter 32-bit.

您可以从一个指针转换为某种函数类型的指针给另一个函数的类型,这也是我建议,如果你需要的函数指针存储在一个数据结构中使用的技术。任何函数类型就可以了。这意味着你不能重新用于数据指针的数据结构。你需要复制的数据结构,并改变它持有的函数指针。

You can cast from a pointer to a certain function type to a pointer to another function type, and this is the technique I recommend you use if you need to store function pointers in a data structure. Any function type will do. This means you cannot reuse a data structure intended for data pointers. You need to duplicate the data structure and change it to hold function pointers.

不要忘了打电话之前投回到正确的函数指针类型,否则这是不确定的行为。

Do not forget to cast back to the proper function pointer type before calling, otherwise this is undefined behavior.

这篇关于ç投无效指针函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆