LoadLibrary:在发布模式下崩溃

LoadLibrary : crash in release mode

我使用 Windows API 中的函数 LoadLibrary 来动态加载 DLL(在发布模式下编译)。然后我调用一个导入函数 my_function

当我的exe被编译成:

这是一个代码示例:

MyClass.cpp:

#include "myclass.h" 

typedef int (__stdcall *f_my_function)(char*, int*); 

MyClass::MyClass()
{
    mDllHandler = NULL;
}

bool MyClass::loadLibrary()
{

    qCritical() << "Loading library";
    mDllHandler = LoadLibrary(L"my.dll");
    qCritical() << "Library loaded";

    if (!mDllHandler) {
        qCritical() << "Error : could not load my.dll";
        return false;
    }

    return true;
}

bool MyClass::freeLibrary()
{
    if(!mDllHandler) {
        qCritical() << "Error : DLL handler is null";
        return false;
    }
    if(!FreeLibrary(mDllHandler)) {
        qCritical() << "Error : could not unload my.dll";
        return false;
    }
    mDllHandler = NULL;

    return true;
}

bool MyClass::myFunction(const& QString str)
{
    if(!mDllHandler) {
        qCritical() << "Error : DLL handler is null";
        return false;
    }
    f_my_function my_function = (f_my_function)GetProcAddress(mDllHandler, "my_function");
    if (!my_function) {
        qCritical() << "Error : Could not resolve the function my_function";
        return false;
    }

    int size = str.size();
    char* string = str.toLatin1().data();

    int error = my_function(string, &size);

    qDebug() << "my_function : Error code is " << error;

    return !error;
}

MyClass.h:

#ifndef MYCLASS_H
#define MYCLASS_H

#include <QString>

class MyClass
{

public:
    MyClass();
    bool loadLibrary();
    bool freeLibrary();
    bool myFunction(const QString& str = "");


private:
    HINSTANCE mDllHandler;


};

#endif // MYCLASS_H

main.cpp

#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyClass myClass;

    myClass.loadLibrary();
    myClass.myFunction();
    myClass.freeLibrary();

    return a.exec();

}

我真的不知道它为什么会在这里崩溃。

编辑:这里我无法访问 my.dll.

的源代码

嗯,崩溃(最终并不总是发生在 LoadLibrary 调用时,但有时会在代码的后面)是由于导入函数的错误声明。

在MyClass.cpp中:

声明错误:

typedef int (__stdcall *f_my_function)(char*, int*);

正确声明:

typedef int (*f_my_function)(char*, int*);

确实我用 __stdcall

错误地声明了 f_my_function