Tom*_*ory 16 c function-pointers void-pointers
在学习了一些教程并阅读有关函数指针的内容后,我了解到显然在ISO C中为函数指针指定了一个void指针是未定义的,有没有办法解决我在编译期间收到的警告(例如更好的编码方式)或我应该忽略它吗?
警告:
ISO C forbids assignment between function pointer and 'void *' [-pedantic]
Run Code Online (Sandbox Code Playgroud)
示例代码:
void *(*funcPtr)();
funcPtr = GetPointer();
Run Code Online (Sandbox Code Playgroud)
GetPointer是一个返回void指针EG的函数
void *GetPointer();
Run Code Online (Sandbox Code Playgroud)
小智 9
在tlpi-book中我发现这个技巧非常有趣:
#include <dlfcn.h>
int
main(int argc, char *argv[])
{
...
void (*funcp)(void); /* Pointer to function with no arguments */
...
*(void **) (&funcp) = dlsym(libHandle, argv[2]);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
编号是正确的,您也是:在C89和C99中,您无法在数据指针(即void *)和函数指针之间进行转换,因此解决警告的唯一方法是从函数返回一个函数指针.
(但请注意,实际上尽管有警告,这仍然有效,即使标准库中存在这种不一致 - 该dlsym()函数用于获取函数指针,但它返回void *- 所以基本上你可以忽略警告.它会工作,虽然严格来说,这里的行为是不明确的.)
小智 5
我在使用glib时遇到了这个问题。Glib 数据结构,例如 GSList,通常有一个名为 void *data 的字段。我想将函数存储在列表中,但遇到了一堆与此类似的错误:
\n\nwarning: ISO C forbids passing argument 2 of \xe2\x80\x98g_slist_append\xe2\x80\x99 between function pointer and \xe2\x80\x98void *\xe2\x80\x99 [-pedantic]\nRun Code Online (Sandbox Code Playgroud)\n\n此示例使用 gcc -Wall -ansi -pedantic 生成一堆警告
\n\ntypedef int (* func) (int);\n\nint mult2(int x)\n{\n return x + x;\n}\n\nint main(int argc, char *argv[])\n{\n GSList *functions = NULL;\n func f;\n\n functions = g_slist_append(functions, mult2);\n f = (func *) functions->data;\n printf("%d\\n", f(10));\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n所以我将函数包装在一个结构中,所有警告都消失了:
\n\nstruct funcstruct {\n int (* func) (int);\n};\n\nint mult2(int x)\n{\n return x + x;\n}\n\nint main(int argc, char *argv[])\n{\n GSList *functions = NULL;\n struct funcstruct p;\n p.func = mult2;\n\n functions = g_slist_append(functions, &p);\n p = * (struct funcstruct *) functions->data;\n printf("%d\\n", p.func(10));\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n可以说,这是相当多的额外代码,可以使一些警告消失,但我不喜欢我的代码生成警告。另外,以上只是玩具示例。在我正在编写的实际代码中,事实证明将函数列表包装在结构中非常有用。
\n\n我很想知道这是否有问题或者是否有更好的方法。
\n| 归档时间: |
|
| 查看次数: |
9688 次 |
| 最近记录: |