ceptonite
ceptonite

Reputation: 21

Function pointer extracted through GetProcAddress crashes the application

Here in my case, I got a function pointer through GetProcAddress of a valid exported function name and as soon as my application calls the exported function, it crashes after displaying the output. If I remove the parameters from the functions and the typdef and pass 19342 directly "getNumChildShapes(19342)" everything works without any crashes.

In my application:

typedef INT (CALLBACK* LPFNDLLFUNC2)(INT modelid);
int codecall()
{
    HINSTANCE hDLL;
    LPFNDLLFUNC2 lpfnDllFunc2;
    INT value = 0;
    INT pass = 19342;

    hDLL = LoadLibrary(L"myDLL");
    if (hDLL != NULL)
    {
        lpfnDllFunc2 = (LPFNDLLFUNC2)GetProcAddress(hDLL, "get_children");
        if (!lpfnDllFunc2)
        {
            // handle the error
            FreeLibrary(hDLL);
            return 0;
        }
        else
        {
            // call the function
            value = lpfnDllFunc2(pass);         
        }
    }
    printf("Children: %i", value);
    FreeLibrary(hDLL);
    return 1;
}

In my dll:

extern "C"
{
    __declspec(dllexport) int get_children(int modelid)
    {
        return getNumChildShapes(modelid);
    }
}

Upvotes: 1

Views: 910

Answers (1)

user31394
user31394

Reputation:

Your function exported from your DLL will be compiled with the C calling convention (__cdecl), but your typedef of the function pointer indicates that you expect to treat it as the Windows calling convention (CALLBACK is a macro for __stdcall). Mixing these two up imbalances the stack.

Either remove CALLBACK from the function pointer declaration, or declare your exported function with __stdcall.

Upvotes: 4

Related Questions