Home > other >  Cannot call DLL function
Cannot call DLL function

Time:08-09

I have been trying to call a DLL that simply displays a MessageBox. I am running into issues where the loader will not locate the function. When the program is running, nothing happens. Tried using user32.dll which I know works for sure. Everything went fine with the SwapMouseButton function. I have defined my imports and exports. Perhaps they were not done properly? Were my calling conversions wrong?

Here are my imports and exports:

#ifndef INDLL_H
#define INDLL_H

#ifdef EXPORTING_DLL
extern __declspec(dllexport) void HelloWorld();
#else
extern __declspec(dllimport) void HelloWorld();
#endif

#endif 

Hello World DLL (trying to display MessageBox from DLL loader):

/* Hello World DLL */
#include "stdafx.h"
#define EXPORTING_DLL
#include "sampleDLL.h"
#include "pch.h"

BOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    return TRUE;
}

void HelloWorld()
{
    MessageBox(NULL, TEXT("Hello World"),
        TEXT("In a DLL"), MB_OK);
}  

DLL Loader (could have wrong conversions):

/* DLL Loader */
#include <windows.h>
#include <iostream>

typedef int(__stdcall* f_funci)();

int main()
{
    HINSTANCE hGetProcIDDLL = LoadLibrary("PATH\\LoadME.dll");

    if (!hGetProcIDDLL) {
        return EXIT_FAILURE;
    }

    // resolve function
    f_funci functon = (f_funci)GetProcAddress(hGetProcIDDLL, "HelloWorld");
    if (!functon) {
        std::cout << "Function Could Not Be Located" << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << "returned " << functon() << std::endl;

    return EXIT_SUCCESS;
} 

CodePudding user response:

Your DLL function does not have a calling convention specified, so it will use the compiler's default, which is most likely __cdecl NOT __stdcall. But your EXE is defining f_funci to use __stdcall. So, even if the function could be found, it likely won't be called correctly.

Double-check the function's name mangling in the DLL's exports table. It i likely being exported as "_HelloWorld" instead of "HelloWorld". Consider using a .DEF file when compiling the DLL in order to control how the function is exported.

Also, consider wrapping the function's declaration in extern "C" when compiling in C .

  • Related