Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class to wrap loadlibrary?

I was thinking it would be cool to have a few classes to wrap around LoadLibrary and GetProcAddress, Library and Function respectively. As I was thinking about this I'm not sure its possible. Here is what I'm thinking:

Library class:

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

    HANDLE getHandle();
    bool isInitialized();
}

And the Function class:

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


    void* call(/* varg arguments? */) throw(exception);

    bool isValid();
}

Problem arises because I have to have dynamic data types for the parameters and multiple lengths to pass to the real function pointer. I could get around the multiple lengths of the arguments by specifying it in the constructor and have specific methods but what about the data types?

EDIT: I've created classes based on the answers for anyone to use here: https://github.com/ic3man5/ice--

like image 634
David Avatar asked Nov 04 '11 07:11

David


2 Answers

You can implement implicit conversion to a function pointer.

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;
};

Use the class as follows:

Function<int (int, double)> foo(library, "foo");
int i = foo(42, 2.0);
like image 143
avakar Avatar answered Nov 19 '22 06:11

avakar


You could look into Qt's QPluginLoader & QLibrary for inspiration.

Regarding calling dynamically loaded functions with arbitrary signature, you could use LibFFI

All this is from a Linux point of view, I don't know Windows and I don't know the equivalent there (but both Qt & LibFFI are ported to Windows)

Notice that calling an arbitrary function thru a pointer can be compiler, processor and ABI specific (hence libFFI contains non-portable code).

like image 1
Basile Starynkevitch Avatar answered Nov 19 '22 07:11

Basile Starynkevitch