在一個名為 test.dll 文件中,有一個 Max() 函數的定義是:
#ifdef BUILD_DLL #define DLL_EXPORT __declspec(dllexport) __stdcall #else #define DLL_EXPORT __declspec(dllimport) __stdcall #endif int DLL_EXPORT Max(int x, int y);
當我在c程序中,定了一個函數指針類型為: int (*func)(int, int) 時
HMODULE h = LoadLibrary("test.dll"); if(h) { int (*func)(int, int) =(int (*)(int, int))GetProcAddress(h, "Max"); printf("max(1,2):%d\n", func(1,2)); }
調用這個函數 func(1,2) 后, windows 並不會馬上報錯,當程序退出時 windows 會報錯:
如果函數指針在定義的時候,加上 WINAPI ,就不會有問題:
#define WINAPI __stdcall HMODULE h = LoadLibrary("test.dll"); if(h) { int (WINAPI *func)(int, int) =(int (WINAPI *)(int, int))GetProcAddress(h, "Max"); printf("max(1,2):%d\n", func(1,2)); }
最后,我的猜測是,之前代碼中沒有加入 WINAPI 在程序退出后, windows 會報錯的原因,應該與 dll 中的 __stdcall 有關。
應該是涉及到 棧(STACK)的清除 問題。
相關資料:
_cdecl 和_stdcall:https://www.cnblogs.com/52yixin/archive/2011/06/29/2093634.html
_stdcall 與 _cdecl:https://blog.csdn.net/nightwizard2030/article/details/86596635
_stdcall與_cdecl區別:https://blog.csdn.net/leehong2005/article/details/8607536