C++动态地将任意函数从DLL加载到std :: function中

Snp*_*nps 8 c++ dll dllexport c++11 std-function

如何使用单个函数将任意动态链接库(dll)函数加载到std::function对象中?

例如,我想将两个函数编译成一个dll:

// test.dll

int plusFive(int value) {
    return value + 5;
}

void printHello() {
    std::cout << "Hello!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

并在运行时使用以下单个函数加载它们:

// main.cc

#include <functional>

int main() {
    std::function<int(int)> func1(loadDllFunc("test.dll", "plusFive"));
    std::function<void()> func2(loadDllFunc("test.dll", "printHello"));
}
Run Code Online (Sandbox Code Playgroud)

Snp*_*nps 8

使用(从MSDN开发人员中心获取的描述)中提供的WinAPI函数.windows.h

  • LoadLibrary - 将指定的模块加载到调用进程的地址空间中.返回模块的句柄.
  • GetProcAddress - 从指定的动态链接库(DLL)中检索导出的函数或变量的地址.返回导出的函数或变量的地址.

使用此函数加载特定函数并返回一个std::function对象:

// main.cc

#include <iostream>
#include <string>
#include <functional>
#include <windows.h>

template <typename T>
std::function<T> loadDllFunc(const std::string& dllName, const std::string& funcName) {
    // Load DLL.
    HINSTANCE hGetProcIDDLL = LoadLibrary(dllName.c_str());

    // Check if DLL is loaded.
    if (hGetProcIDDLL == NULL) {
        std::cerr << "Could not load DLL \"" << dllName << "\"" << std::endl;
        exit(EXIT_FAILURE);
    }

    // Locate function in DLL.
    FARPROC lpfnGetProcessID = GetProcAddress(hGetProcIDDLL, funcName.c_str());

    // Check if function was located.
    if (!lpfnGetProcessID) {
        std::cerr << "Could not locate the function \"" << funcName << "\" in DLL\"" << dllName << "\"" << std::endl;
        exit(EXIT_FAILURE);
    }

    // Create function object from function pointer.
    std::function<T> func(reinterpret_cast<__stdcall T*>(lpfnGetProcessID));

    return func;
}
Run Code Online (Sandbox Code Playgroud)

DLL源应该像这样写:

// test.cc (test.dll)
#include <iostream>

// Declare function prototypes with "extern C" to prevent name mangling.
// Declare functions using __declspec(dllexport) to signify the intent to export.
extern "C" {
    __declspec(dllexport) int __stdcall plusFive(int);
    __declspec(dllexport) void __stdcall printHello();
}

int plusFive(int value) {
    return value + 5;
}

void printHello() {
    std::cout << "Hello!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

然后loadDllFunc像这样使用:

// main.cc

int main() {
    auto func1 = loadDllFunc<int(int)>("test.dll", "plusFive");
    auto func2 = loadDllFunc<void()>("test.dll", "printHello");

    std::cout << "Result of func1: " << func1(1) << std::endl;
    func2();
}
Run Code Online (Sandbox Code Playgroud)

输出:

Result of func1: 6
Hello!
Run Code Online (Sandbox Code Playgroud)

作为旁注,可以使用GCC(4.7.2)编译DLL,如下所示:

g++ -shared -o test.dll test.cc -std=c++11
Run Code Online (Sandbox Code Playgroud)

编辑:

我不确定强制转换是否loadDllFunc给出了正确的类型:

std::function<T> func(reinterpret_cast<__stdcall T*>(lpfnGetProcessID));
Run Code Online (Sandbox Code Playgroud)

似乎应该把它投到它应该的__stdcall int (*)(int)时候int (__stdcall *)(int).

这是loadDllFunc使用辅助解析器类实现的另一种方法.此解决方案将正确地将函数指针强制转换为int (__stdcall *)(int).

template <typename T>
struct TypeParser {};

template <typename Ret, typename... Args>
struct TypeParser<Ret(Args...)> {
    static std::function<Ret(Args...)> createFunction(const FARPROC lpfnGetProcessID) {
        return std::function<Ret(Args...)>(reinterpret_cast<Ret (__stdcall *)(Args...)>(lpfnGetProcessID));
    }
};

template <typename T>
std::function<T> loadDllFunc(const std::string& dllName, const std::string& funcName) {
    // Load DLL.
    HINSTANCE hGetProcIDDLL = LoadLibrary(dllName.c_str());

    // Check if DLL is loaded.
    if (hGetProcIDDLL == NULL) {
        std::cerr << "Could not load DLL \"" << dllName << "\"" << std::endl;
        exit(EXIT_FAILURE);
    }

    // Locate function in DLL.
    FARPROC lpfnGetProcessID = GetProcAddress(hGetProcIDDLL, funcName.c_str());

    // Check if function was located.
    if (!lpfnGetProcessID) {
        std::cerr << "Could not locate the function \"" << funcName << "\" in DLL\"" << dllName << "\"" << std::endl;
        exit(EXIT_FAILURE);
    }

    // Create function object from function pointer.
    return TypeParser<T>::createFunction(lpfnGetProcessID);
}
Run Code Online (Sandbox Code Playgroud)