为什么调用 SetConsoleCtrlHandler() 会触发警告?
Why calling SetConsoleCtrlHandler() triggers a warning?
#include <windows.h>
BOOL MyCtrlHandler(DWORD ctrlType) {
return TRUE;
}
int main(void) {
SetConsoleCtrlHandler(MyCtrlHandler, TRUE);
return 0;
}
函数签名匹配 doc:
The PHANDLER_ROUTINE type defines a pointer to this callback function. HandlerRoutine is a placeholder for the application-defined function name.
如果我用 64 位的 MinGW 交叉编译它,它可以工作:
$ x86_64-w64-mingw32-gcc ctrl.c
$
但是在 32 位中,我收到警告:
$ i686-w64-mingw32-gcc ctrl.c
ctrl.c: In function ‘main’:
ctrl.c:8:27: warning: passing argument 1 of ‘SetConsoleCtrlHandler’ from incompatible pointer type [-Wincompatible-pointer-types]
8 | SetConsoleCtrlHandler(MyCtrlHandler, TRUE);
| ^~~~~~~~~~~~~
| |
| BOOL (*)(DWORD) {aka int (*)(long unsigned int)}
In file included from /usr/share/mingw-w64/include/windows.h:74,
from ctrl.c:1:
/usr/share/mingw-w64/include/wincon.h:249:68: note: expected ‘PHANDLER_ROUTINE’ but argument is of type ‘BOOL (*)(DWORD)’ {aka ‘int (*)(long unsigned int)’}
249 | WINBASEAPI WINBOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE HandlerRoutine,WINBOOL Add);
|
$
我不明白为什么,因为MyCtrlHandler
应该和PHANDLER_ROUTINE
有相同的类型。
这里的问题是__cdecl和__stdcall的区别。在一次成功的编译尝试中,您一定很幸运地使用了默认调用约定。您需要:
BOOL WINAPI MyCtrlHandler(DWORD ctrlType) {
return TRUE;
}
#include <windows.h>
BOOL MyCtrlHandler(DWORD ctrlType) {
return TRUE;
}
int main(void) {
SetConsoleCtrlHandler(MyCtrlHandler, TRUE);
return 0;
}
函数签名匹配 doc:
The PHANDLER_ROUTINE type defines a pointer to this callback function. HandlerRoutine is a placeholder for the application-defined function name.
如果我用 64 位的 MinGW 交叉编译它,它可以工作:
$ x86_64-w64-mingw32-gcc ctrl.c
$
但是在 32 位中,我收到警告:
$ i686-w64-mingw32-gcc ctrl.c
ctrl.c: In function ‘main’:
ctrl.c:8:27: warning: passing argument 1 of ‘SetConsoleCtrlHandler’ from incompatible pointer type [-Wincompatible-pointer-types]
8 | SetConsoleCtrlHandler(MyCtrlHandler, TRUE);
| ^~~~~~~~~~~~~
| |
| BOOL (*)(DWORD) {aka int (*)(long unsigned int)}
In file included from /usr/share/mingw-w64/include/windows.h:74,
from ctrl.c:1:
/usr/share/mingw-w64/include/wincon.h:249:68: note: expected ‘PHANDLER_ROUTINE’ but argument is of type ‘BOOL (*)(DWORD)’ {aka ‘int (*)(long unsigned int)’}
249 | WINBASEAPI WINBOOL WINAPI SetConsoleCtrlHandler(PHANDLER_ROUTINE HandlerRoutine,WINBOOL Add);
|
$
我不明白为什么,因为MyCtrlHandler
应该和PHANDLER_ROUTINE
有相同的类型。
这里的问题是__cdecl和__stdcall的区别。在一次成功的编译尝试中,您一定很幸运地使用了默认调用约定。您需要:
BOOL WINAPI MyCtrlHandler(DWORD ctrlType) {
return TRUE;
}