包装loadlibrary的c++类

C++ class to wrap loadlibrary?

本文关键字:c++ loadlibrary 包装      更新时间:2023-10-16

我认为有几个类分别围绕LoadLibraryGetProcAddress, LibraryFunction将是很酷的。当我在思考这个问题时,我不确定这是否可能。我是这么想的:

Library class:

class Library
{
    HANDLE m_handle;
public:
    // Handles initializing the DLL:
    Library(std::string name);
    // Deinitializes the DLL
    ~Library();
    HANDLE getHandle();
    bool isInitialized();
}

Function类:

class Function
{
public:
    Function(Library& library, std::string name);

    void* call(/* varg arguments? */) throw(exception);
    bool isValid();
}
问题出现了,因为我必须有动态数据类型的参数和多个长度传递给真正的函数指针。我可以通过在构造函数中指定参数并使用特定的方法来解决参数的多个长度问题但是数据类型呢?

编辑:我已经根据答案创建了类,供任何人在这里使用:https://github.com/ic3man5/ice--

可以实现隐式转换为函数指针。

template <typename Signature>
struct Function
{
    Function(Library& library, std::string name)
    {
        m_func = reinterpret_cast<Signature *>(
            ::GetProcAddress(library.m_hModule, name.c_str()));
    }
    operator Signature *() { return m_func; }
private:
    Signature * m_func;
};

按如下方式使用类:

Function<int (int, double)> foo(library, "foo");
int i = foo(42, 2.0);

你可以看看Qt的QPluginLoader &QLibrary .

关于调用带有任意签名的动态加载函数,您可以使用LibFFI

所有这些都是从Linux的角度来看,我不知道Windows,我不知道等效的(但两者都是Qt &LibFFI被移植到Windows)

请注意,通过指针调用任意函数可能是编译器、处理器和ABI特定的(因此libFFI包含不可移植的代码)。