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--
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With