簡體   English   中英

運行時加載dll

[英]Loading dll at runtime

我需要在運行時加載一個 DLL。 我事先不知道要加載哪個 DLL,但 DLL 是接口的實現(純虛方法)。 最終目標是擁有一個指向 DLL 的指針來調用其方法。

現在,我只想測試 DLL 加載,調用測試方法,但我失敗了。 測試方法是void test()

#if defined (_WIN32)
const path PluginExtension(".dll");
#define STDCALL __stdcall
#else
const path PluginExtension(".so");
#define STDCALL
#endif

extern "C"
{    
    typedef void*  (STDCALL* CreatorFunction)();
        
    constexpr auto FunctionName{ "CommandGeneratorEngine::Interface::test" };
}

auto library = LoadLibraryExW(pluginPath.native().c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (library != nullptr) {
                
    auto creator = (CreatorFunction)GetProcAddress(library, FunctionName);
    if (creator != nullptr) {
        // do something 
    }
    else
    {
        throw std::exception("Error when loading comm plugin");
    }

界面

namespace TGComm {
namespace CommandGeneratorEngine {
    
class Interface {
public:
        
    using Ptr = std::shared_ptr<Interface>;
    virtual ~Interface() = default;
    
    virtual  void test() = 0;
         
};

}
}

以及接口實現:

class LHFImplementationInterface : public CommandGeneratorEngine::Interface
{
public:

    void __declspec(dllexport) __stdcall test() override{
        // do something...
    }
};

auto creator = (CreatorFunction)GetProcAddress(library, FunctionName);

返回一個空值。

解決了。

我創建了一個新的頭文件 h1.h

#include "Global.h"

extern "C" {

LHCOMMQT_LIB void* createTGCommPlugin();

}

它的 cpp 是

#include "h1.h"
#include "LHFImplementationinterface.h"

void* createTGCommPlugin() {
    auto p = new LHFImplementationInterface();
    return p;
}

和 global.h 是

#ifndef LHCOMM_GLOBAL_H
#define LHCOMM_GLOBAL_H

#include <QtCore/qglobal.h>

#ifdef LHCOMMQT_EXPORTS
# define LHCOMMQT_LIB Q_DECL_EXPORT
#else // ifdef LHCOMMQT_EXPORTS
# define LHCOMMQT_LIB Q_DECL_IMPORT
#endif // ifdef LHCOMMQT_EXPORTS

#endif // LHCOMM_GLOBAL_H

在主要:

typedef void* (STDCALL* CreatorFunction)();
constexpr auto FunctionName{ "createTGCommPlugin" };
try {
    auto library = LoadLibraryExW(pluginPath.native().c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
    if (library != nullptr) {
    
        auto creator = (CreatorFunction)GetProcAddress(library, FunctionName);
...

現在效果很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM