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