Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to load DLL functions?

Tags:

c++

c

windows

dll

I feel like there's a much, much better way than just having hundreds of signatures in typedefs, and then loading pointers by GetProcAddress. As far as I know, it is the easiest -- but dirty -- when it comes to loading DLL functions.

Is there a less messy way to load DLL functions? Specifically, a large amount of Winapi and Tool Help library functions? I know you can just "include a .lib," but I feel like that would cause unnecessary bloat; nor do I have access to the source code (although Jason C mentioned it is possible to go from a .dll to a .lib).

I was looking to code a library for this. I feel like the major roadblock is dealing with functions that have varying signatures; or is this precisely the reason why everyone uses typedefs instead of "some fanciful loop" to load their DLL functions?

like image 624
Saustin Avatar asked Feb 15 '23 16:02

Saustin


1 Answers

Your functions have to be declared somehow, so you need the function signatures. But, if you feel you are duplicating the function signatures, you can use decltype(&func_name) to eliminate that duplication (given a function func_name with the same target signature). You can wrap that in a macro to make it more palatable.

Another common approach is to shove all the function pointers into one big struct (or a bunch of task-specific structs), and load a pointer to the struct instead (e.g. by loading a function that returns a pointer to the struct). This looks like the following:

Common header

struct func_table {
    void (*f1)(int);
    int (*f2)(void);
};

DLL

static struct func_table table = {
    &f1_Implementation,
    &f2_Implementation,
};

DLLEXPORT struct func_table *getFuncTable(void) {
    return &table;
}

Program using the DLL

static struct func_table *funcs;

void loadFuncTable() {
    struct func_table (*getFuncTable)(void) = GetProcAddress(..., "getFuncTable");
    funcs = getFuncTable();
}

/* call funcs->f1(n) and funcs->f2() */
like image 97
nneonneo Avatar answered Feb 23 '23 05:02

nneonneo