Home > Software engineering >  Calling a function in a .dll with GetProcAddress
Calling a function in a .dll with GetProcAddress

Time:09-04

How can I successfully cast MYPROC, which is a pointer to a function: typedef void(*MYPROC)(LPCWSTR); to (MYPROC)GetProcAddress(getdll, "myPuts");?

Considering that GetProcAddress() returns FARPROC, which is a function pointer that takes no parameter, and MYPROC takes one parameter and FARPROC no parameters, how can the cast be successful?

typedef void(*MYPROC)(LPCWSTR); //you must set a function pointer to call the function in the .dll

int main(void)
{
    HINSTANCE getdll;
    MYPROC getprocadd;
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
    
    getdll = LoadLibrary(TEXT("myPuts.dll"));  // Get a handle to the DLL module.
    if (getdll == NULL) {
        exit(2);
    }
    
    if (getdll != NULL)  // If the handle is valid, try to get the function address.
    {
       getprocadd = (MYPROC)GetProcAddress(getdll, "myPuts"); //GetProcAddress returns FARPROC (a function pointer for a function that takes no parameters: (FAR WINAPI *FARPROC)())

        if (NULL != getprocadd)  // If the function address is valid, call the function.
        {
            fRunTimeLinkSuccess = TRUE;
            (getprocadd)(L"Message from the .dll file's function: myPuts\n");
        }

        fFreeResult = FreeLibrary(getdll);  // Free the DLL module.
    }

    // If unable to call the DLL function, use an alternative.
    if (!fRunTimeLinkSuccess)
        printf("Message printed from executable: printf\n");

    return 0;
}

CodePudding user response:

how can the cast be successful?

Because the C language standard allows a function pointer to be casted to another function pointer type. GetProcAddress() just returns a raw pointer to the function, what is important is that the type you are casting to must match the actual function that is inside the DLL. If it doesn't, you will end up invoking undefined behavior when you call the function via the casted pointer.

  • Related