首页 > 解决方案 > 调用 dll 函数时出现“运行时检查失败 #0 - ESP 的值”

问题描述

我有一个带有 lib.h 的 dll:

#pragma once

#ifdef EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif

extern "C" API void test1(std::vector<ValueType*>* functions);

和 lib.cpp:

#include "pch.h"
#include <iostream>
#include <vector>

#include "ValueType.h"
#include "NumberValue.h"

#include "TestLib.h"

void test1(std::vector<ValueType*>* functions) {
    functions->push_back(new NumberValue(123321));

使用此 dll 的主文件是:

#include <iostream>
#include <vector>
#include <Windows.h>


#include "ValueType.h"


using namespace std;


typedef void (WINAPI* importedInitFunction)(std::vector<ValueType*>*);
importedInitFunction test1F;

std::vector<ValueType*> values;


int main() {
    while (1) {
        HMODULE lib = LoadLibrary("DllTest1.dll");


        test1F = (importedInitFunction)GetProcAddress(lib, "test1");

        test1F(&values);
        test1F(&values);

        std::cout << values.at(0)->asString();

        FreeLibrary(lib);
        system("pause");
    }
    return 0;
}

当我试图编译我的代码时,我发现错误说:“运行时检查失败 #0 - ESP 的值没有在函数调用中正确保存。”,在“test1F(&values);”行。

如何解决?

标签: c++winapidll

解决方案


问题是在主程序中您声明了WINAPI扩展为的函数指针__stdcall,但默认调用约定(由 DLL 使用)是__cdecl.

调用约定中的这种不匹配是导致您出现问题的原因。要解决它,请删除WINAPI宏,或使 DLL 函数 WINAPI.


推荐阅读