【发布时间】:2013-04-08 05:12:21
【问题描述】:
在函数指针和对象指针之间显然是一般意义上的未定义行为,但 POSIX(参见:dlsym)和 WinAPI(参见:GetProcAddress)要求这样做。
鉴于此,并且考虑到此类代码无论如何都针对特定于平台的 API,它对函数指针和对象指针不兼容的平台的可移植性确实无关紧要。
但是 -Wpedantic 无论如何都会发出警告,#pragma GCC diagnostic ignored "-Wpedantic" 没有效果:
warning: ISO C++ forbids casting between pointer-to-function and pointer-to-object [enabled by default]
我想保持启用 -Wpedantic,因为它确实给出了很好的警告,但我不想让真正的警告和错误丢失在关于函数指针到对象指针的不相关警告的海洋中演员表。
有没有办法做到这一点?
在 Windows (MinGW) 上运行 GCC 4.8.0:
gcc (rubenvb-4.8.0) 4.8.0
代码示例
#include <windows.h>
#include <iostream>
int main (void) {
std::cout << *reinterpret_cast<int *>(GetProcAddress(LoadLibraryA("test.dll"),"five")) << std::endl;
}
发射(使用 -Wpedantic):
warning_demo.cpp: In function 'int main()':
warning_demo.cpp:7:87: warning: ISO C++ forbids casting between pointer-to-funct
ion and pointer-to-object [enabled by default]
std::cout << *reinterpret_cast<int *>(GetProcAddress(LoadLibraryA("test.dll"),
"five")) << std::endl;
^
【问题讨论】:
-
我在转换
GetProcAddress的结果时从来没有遇到过问题。 -
您是否有任何生成该警告的代码可以发布?
-
@WhozCraig 已添加到问题中。
-
test.dll包含int five=5。编译并运行程序时,只打印“5”。这是一个有效的用例,GetProcAddress: "Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL)." 特别允许 -
这在运行时运行良好。使用
extern "C"可以避免名称修改问题。这只是编译器有问题的演员,而且是在编译时。
标签: c++ gcc c++11 mingw gcc-pedantic