0

I have following code:

typedef int (WINAPI* fnEngineStart)();


int __stdcall EngineStart()
{
BOOL FreeResult = 0, RunTimeLinkSuccess = 0; //variables for later use
HMODULE LibraryHandle = 0; //Here the handle to API module/dll will be stored.
fnEngineStart fn = 0;

LibraryHandle = AfxLoadLibrary(L"FlowEngine.dll"); //get the handle of our API module
//so it will now be loaded.
if (LibraryHandle != NULL) //if the library loading was successfull..
{
    fn = (fnEngineStart)GetProcAddress(LibraryHandle,
        "fnEngineStart");
    if (RunTimeLinkSuccess = (fn != NULL)) //if operation was successful...
    {
        int ReturnValue = fn(); //call messageboxa function
        //from user32.dll
    }
    else
    {
        MessageBox(0, L"Error", 0, 0);
    }
    FreeResult = FreeLibrary(LibraryHandle);
    //from this process...
    return FreeResult; //routine was successful
}
return EXIT_FAILURE; //else, it failed
}

This code works perfectly for example user32.dll and MessageBoxA but not my own dll...

int __declspec(dllexport) __stdcall fnEngineStart()
{
   MessageBox(0, L"Succes!", 0, 0);
   return 0;
}

How do I make this to work for my own dll as well? Thanks in advance.

2
  • GetProcAddress sets a value for GetLastError ...
    – Alex K.
    Feb 5, 2016 at 14:26
  • And that error code will be 127. Because the function name is decorated. Potentially with C++ mangling, but certainly stdcall decoration. Either use a .def file, or, better, let the name be mangled and import it using its mangled name. Feb 5, 2016 at 14:42

1 Answer 1

0

The issue you are dealing with is Name Mangling. Use extern "C" so the compiler doesn't mangle the name. Example:

extern "C" int __declspec(dllexport) __stdcall fnEngineStart()
{
   MessageBox(0, L"Succes!", 0, 0);
   return 0;
}

Note: __stdcall functions are name-decorated with a leading underscore, followed by an @, and then the number (in bytes) of arguments passed on the stack. This number will always be a multiple of 4, on a 32-bit aligned machine. Source

If your compiler supports it, you can do this in your dll and everything should work the way you have it now.

extern "C" int __declspec(dllexport) __stdcall fnEngineStart()
{
   #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
   MessageBox(0, L"Succes!", 0, 0);
   return 0;
}
1
  • 1
    There's more to it than that. The function will be exported decorated as _fnEngineStart@0. You'd need to use a .def file or switch to cdecl to avoid that decoration. Or just import the function with its correct name. Feb 5, 2016 at 14:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.