怎样沉默的函数指针的C编译器接受任意数量的参数? [英] How do I quiet the C compiler about a function pointer takes any number of arguments?

查看:165
本文介绍了怎样沉默的函数指针的C编译器接受任意数量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我里面有一个函数指针结构,获取动态设置在运行时在我的code不同的地方的另一个函数的地址。它在我的头文件中定义如下:

I have a function pointer inside a struct that gets dynamically set at runtime to the address of another function in various places in my code. It is defined in my header file like this:

    void *(*run)();

在编译的时候,我得到这个以下警告:

During compile time, I get the following warning about this:

    warning: function declaration isn't a prototype

这警告是良性的,因为指针在很多地方使用我的code调用它指向的功能,一切工作就好了。不过,我的真正的喜欢沉默的警告。

This warning is benign, because the pointer is used in many places in my code to call the function it points to, and everything works just fine. However, I would really like to silence the warning.

如果我把它改成这样:

    void *(*run)(void);

我得到whever我用它编译错误,因为利用指针的各种功能都有的参数不同的号码,并说无效的parenthesies里面告诉编译器它不接受任何参数。

I get compile errors whever I use it, because the various functions that make use of the pointer have different numbers of arguments, and saying void inside the parenthesies tells the compiler it accepts no arguments.

我不能使用的va_list 或任何幻想这样的,因为这是只是一个指针给另一个函数,我用一个指针,为他们所有,因为它保持code干净和简单。

I can't use a va_list or anything fancy like that, as this is simply a pointer to another function, and I use a single pointer for them all because it keeps the code clean and simple.

我可以将其加入我的编译器标志沉默警告:

I can silence the warning with adding this to my compiler flags:

    -Wno-strict-prototypes

但我宁愿没有用旗帜来禁用编译器警告,如果我能避免它。

But I'd rather not have to disable compiler warnings with flags if I can avoid it.

所以我的问题是:如何notate在这样的方式code这个函数指针编译器是满意的,它接受任何数目的任何形式的论点的事实

在code完美的作品。我只是想警告走开。

The code works perfectly. I just want the warning to go away.

推荐答案

存放指针作为无效* 和转换为相应的函数指针类型在必要的时候?请记住,它并不一定是安全调用一种类型的函数指针就好像它是另一种类型,所以你开始接触警告也不是完全无效的。

Store the pointer as a void * and cast to the appropriate function pointer type when necessary? Keep in mind that it isn't necessarily safe to call one type of function pointer as if it were another type, so the warning you're starting out with isn't entirely invalid.

您可以投一个函数指针像这样:

You can cast a function pointer like so:

void *genericPointer = ...;
void (*fp)(int, int) = genericPointer;
fp(123, 456);

需要注意的是:


  • 有没有必要明确铸造这里,为无效* 总是可以被转换为任何指针类型。

  • 最初的作废之前(* FP)是函数指针的返回类型。

  • There's no explicit casting necessary here, as void * can always be cast to any pointer type.
  • The initial "void" before (*fp) is the return type of the function pointer.

这篇关于怎样沉默的函数指针的C编译器接受任意数量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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