【问题标题】:LoadLibrary : crash in release mode [closed]LoadLibrary:在发布模式下崩溃[关闭]
【发布时间】:2018-12-31 18:46:37
【问题描述】:

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

当我的 exe 被编译时:

  • 调试模式:没问题
  • 带有调试信息的发布模式:没问题
  • RELEASE 模式不带调试信息:当我调用导入的函数my_function 时,它在调用LoadLibrary 后崩溃

这是一个代码示例:

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

ma​​in.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 的源代码。

【问题讨论】:

  • 也许,你的DllMain 或my.dll 中生活着什么恐怖?
  • “它崩溃了” 是什么意思?它在哪里“崩溃”?发生故障时的调用堆栈是什么?
  • 这个问题很遗憾地漏掉了相关的细节。提供的代码很好,只要加载的库编码正确。问题出在那个库上,但我们对此一无所知。
  • 我已经更新了我的问题,使其更加清晰。

标签: c++ winapi release


【解决方案1】:

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

在 MyClass.cpp 中:

错误声明:

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

正确声明:

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

确实,我错误地将f_my_function 声明为__stdcall

【讨论】:

  • 不回答问题。问题中的代码不导入任何功能。它只是调用LoadLibrary。
  • 如果将参数名称添加到类型定义中以提高可读性会更好。不能忍受没有参数名称的类型定义。
猜你喜欢
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多