调用 Dll 中的函数时,出现栈(STACK)的清除问题 -> 故障模块名称: StackHash_0a9e

在一个名为 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
", 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
", 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

原文地址:https://www.cnblogs.com/personnel/p/11314639.html