作者:dx152 | 来源:互联网 | 2023-09-12 13:05
某项目要调用一个第三方的 Windows 动态库(DLL),这个 DLL 除了一份简单的 API 文档,没有任何参考代码。用 VC++ 写了测试程序,通过 LoadLibrary、GetProcAddress 得到 DLL 中的 API 函数地址进行调用,一开始是按 Release 配置编译,结果调用该 DLL 中的函数可以得到正确结果,但之后总是闪退(也就是 crash),不报任何错。由于没有该 DLL 的源码,无法定位 crash 原因,无法确定是否由于调用参数不正确还是由于该 DLL 本身的 bug 导致的 crash。后来改成 Debug 配置编译测试程序,结果一启动就直接弹框报错:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
原来是跟 calling convention 不一致有关,根据网上的相关文章,在定义 DLL 中的 API 函数的函数指针的地方添加了关键字 __stdcall,就像这样:
typedef int (__stdcall * func)(void);
修改后程序正常运行,不再 crash。