代码之家  ›  专栏  ›  技术社区  ›  bam500

LoadLibrary:在释放模式下崩溃[关闭]

  •  -3
  • bam500  · 技术社区  · 8 年前

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

    当我的exe编译在:

    • 调试模式 没有问题
    • 带调试信息的发布模式 没有问题
    • 释放模式,不带调试信息 :它在 加载 调用,当我调用导入的函数时 My-函数

    以下是代码示例:

    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
    

    主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源代码的权限。

    1 回复  |  直到 8 年前
        1
  •  -1
  •   bam500    8 年前

    好吧,崩溃(最终并不总是在loadlibrary调用时发生,但有时在代码的后面)是由于对导入函数的错误声明造成的。

    在myclass.cpp中:

    声明错误:

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

    正确声明:

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

    事实上,我错报了 f_my_function 具有 __stdcall