1

I am writing a C program to call a DLL, but the typelist and return value are unknown. I found a way to bypass this: by not casting to any function.

//todll.c

int test(int arg1, int arg2) {
  return arg1 + arg2;
}
//caller.c
#include <windows.h>

int main() {
  HMODULE module = LoadLibrary("test.dll"); //load the library into an HMODULE
  FARPROC proc = GetProcAddress(module, "test"); //get the process
  printf("%d", proc((void*) 9), ((void*) 10);
}

And this works. But the issue is that the users can enter different argument lengths. I store the length of the arguments in a variable called argc (type int), and the actual arguments in a variable argv (type void**). Now I want to pass the argv to the dll.

I know i can do something like

switch (argc) {
  case 0:
    return proc();
  case 1:
    return proc(argv[0]);
  case 2:
    return proc(argv[0], argv[1]);
  case 3:
    return proc(argv[0], argv[1], argv[2]);

  //etc...
  case 127:
    return proc(argv[0], argv[1], argv[2], argv[3], argv[4], /* etc... */, argv[126]);
}

But I think that there should be a better way to accomplish this.

1 Answer 1

1

First, the proper way to handle your existing function is to cast the return value of GetProcAddress to the proper type:

int (*proc)(int, int) = (int (*)(int, int))GetProcAddress(module, "test");

Then you can call it properly:

printf("%d", proc(9, 10));

As for how to handle multiple values, change the library function to accept a length parameter and a pointer pointing to the start of an array:

int test(int argc, void **argv) {
  int sum = 0;
  int i;

  for (i=0;i<argc;i++) {
      sum += *((int *)(argv[i]));
  }
  return sum;
}

And pass argc and argv to your function.

Sign up to request clarification or add additional context in comments.

7 Comments

is there any way to replace int test(int argc, void** argv) with just int test(int val1, int val2)?
@Ankizle If you do that, you'll only be able to pass two values of type int.
Yes, but there are multiple functions in that dll and the user decides which function to call.
@Ankizle Are the functions in any way related? If so you might be able to consolidate them. Otherwise, you would need to figure out which one to call and call that one explicitly.
@Ankizle Again, it depends on the functions you want to call and how they are related. You might want to update your question with more detail, giving more concrete examples of these functions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.