user3192654
user3192654

Reputation: 3

How do I call a function from my DLL during run-time linking?

I do not understand DLLs very well, so I've constructed a simple example that I woudl like some help with. I have a simple dll here.

// HelloDLL.cpp

#include "stdafx.h"

int     __declspec(dllexport)   Hello(int x, int y);    

int Hello(int x, int y)
{
    return (x + y);
}

How would I call the Hello(int x, int y) function in a separate program once I've run LoadLibrary()? Here's a rough layout of what I have so far but I'm not sure if what I have is correct, and if it is, how to proceed.

// UsingHelloDLL.cpp

#include "stdafx.h"
#include <windows.h> 

int main(void) 
{ 
    HINSTANCE hinstLib;  

    // Get the dll
    hinstLib = LoadLibrary(TEXT("HelloDLL.dll")); 

    // If we got the dll, then get the function
    if (hinstLib != NULL) 
    {
        //
        // code to handle function call goes here.
        //

        // Free the dll when we're done
        FreeLibrary(hinstLib); 
    } 
    // else print a message saying we weren't able to get the dll
    printf("Could not load HelloDLL.dll\n");

    return 0;
}

Could anyone help me out on how to handle the function call? Any special cases I should be aware of for future usage of dlls?

Upvotes: 0

Views: 137

Answers (1)

user3195397
user3195397

Reputation: 236

After loading the library, what you need is to find the function pointer. The function Microsoft provides is GetProcAdderess. Unfortuantely, you have to know function prototype. If you don't knwo, we are going all the way to COM/DCOM, etc. Probably out of your scope.

FARPROC WINAPI GetProcAddress( _In_  HMODULE hModule, _In_  LPCSTR lpProcName ); 

So in your example, what you do nromally is like this:

typedef int (*THelloFunc)(int,int);  //This define the function prototype

if (hinstLib != NULL) 
{
    //
    // code to handle function call goes here.
    //

    THelloFunc f = (THelloFunc)GetProcAddress(hinstLib ,"Hello");

    if (f != NULL )
        f(1, 2);

    // Free the dll when we're done
    FreeLibrary(hinstLib); 
} 

Upvotes: 1

Related Questions