C4theWin
C4theWin

Reputation: 133

How can I call a function from a dll?

How could I call a function from a DLL?

I tried to declare a void pointer and to store in it the result of GetProcAddress... but didn't work. I also wanted to declare an unsigned long int (I saw it somewhere on the internet), but then I didn't know how to continue on. :D

So, would anybody mind giving me a hand?

Upvotes: 0

Views: 587

Answers (3)

Greg Domjan
Greg Domjan

Reputation: 14105

Try for something like this.

typedef int (*PFuncMethods)( int args );

hDLL  = LoadLibrary(L"your.dll");
if( !m_hDLL )
  return;

methods = (PFuncMethods)GetProcAddress(hDLL,"methods");
if ( !(methods) ) {
  FreeLibrary(hDLL);
  hDLL = NULL;
  methods = NULL;
  return;
} 

if( methods(1) == 0) ...

the method name is where you might be stuck aswell. C++ has name mangling for overloading (even if it's not overloaded) and that depends on the compiler. You can either work out the mangled name or turn off mangling for the function by using extern "C". You might use a tool like depends.exe to see all the functions with exact name you would have to use.

It is much easier to statically link to the DLL using the (import)lib file in windows.

Upvotes: 2

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19114

You need to have exact function signature, and to cast the pointer properly.

For exmaple, if this is a function receiving int and returning void:

typedef void (*funcptr)(int);
funcptr func = (funcptr)(void*)GetProcAddress(....)
func(17);

Note1: If you confuse the signature, very bad things can happen. Note2: you also need to know the calling convention used (cdecl, stdcall, etc..)

If it's your DLL, better consider making an import library instead.

Upvotes: 1

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

You have to create a function pointer not a void pointer and store the result in that function pointer from GetProcAddress.

Upvotes: 1

Related Questions