2

Im trying to call an exported function from a DLL by grabbing its function pointer through GetProcAddress but upon calling the function the application crashes.

I used dependencywalker to see if the exported functions have the correct name. The address returned from GetProcAddress is not null. I'm almost certain that it has something to do with the calling convention, i used both __cdecl and __stdcall but no success. However i do would like to use GetProcAdress instead of __declspec(dllimport).

DLL #1 (Caller)

  • Linked DLL#2.lib to this DLL

    typedef void(__stdcall *ptr_init)(DWORD size);
    
    ctx.hModule = LoadLibraryA("someDLL.dll");
    ptr_init init = (ptr_init)GetProcAddress(ctx.hModule, "init");
    
    if (init == NULL) {
        out = out + " | init function is null";
    } else {
        out = out + " | init function found!";//It is found
    }
    
    DWORD test = 10;
    (*init)(test);//<-- makes application crash
    

DLL #2 (DLL containing exported function)

//header.h
extern "C" __declspec(dllexport) void init(DWORD size);

//source.cpp
extern "C" __declspec(dllexport) void init(DWORD size) {
    //code
}
MircoProgram
  • 295
  • 1
  • 20
  • 2
    You don't have the compiler to help you when you get it wrong. Looks like you got it wrong, that doesn't look very __stdcall. Otherwise no compelling reason to avoid using the debugger. – Hans Passant Sep 05 '16 at 12:54
  • The function is cdecl. Why did you use stdcall. Can't you write init(test). Problem is likely in your DLL. Consider creating a MCVE. – David Heffernan Sep 05 '16 at 12:54
  • *"However i do would like to use `GetProcAdress` instead of `__declspec(dllimport)`."* - Why would that be? If all you need is control over when, and how imports are resolved, you could use [delay-loading](https://msdn.microsoft.com/en-us/library/151kt790.aspx), and handle import resolution in your code (see [Understanding the Helper Function](https://msdn.microsoft.com/en-us/library/09t6x5ds.aspx)). – IInspectable Sep 05 '16 at 13:54

1 Answers1

3

You should be consistent. If you retrieve pointer as a pointer to stdcall function - it must be declared as stdcall in implementation:

//header.h
extern "C" __declspec(dllexport) void __stdcall init(DWORD size);
Sergio
  • 8,099
  • 2
  • 26
  • 52