c++winapidllicc

Error with compiling DLL with intel compiler


I'm trying to compile DLL from console, without using any IDE and faced with next error.

I wrote this code:

test_dll.cpp

#include <windows.h>
#define DLL_EI __declspec(dllexport)

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved){
  return 1;
}
extern "C" int DLL_EI func (int a, int b){
  return a + b;
}

Then compiled with command icl /LD test_dll.cpp. And I'm trying to call this func from another program:

prog.cpp

int main(){
  HMODULE hLib;
  hLib = LoadLibrary("test_dll.dll");  
  double (*pFunction)(int a, int b);
  (FARPROC &)pFunction = GetProcAddress(hLib, "Function");
  printf("begin\n");
  Rss = pFunction(1, 2);
}

Compile it with icl prog.cpp. Then I run it, and it fails with standard window "Program isn't working". Maybe there is a segmentation fault error.

What am I doing wrong?


Solution

  • Check that both LoadLibrary() and GetProcAddress() succeed, in this case they definitely will not as the exported function is called func, not "Function" as specified in the argument to GetProcAddress() meaning the function pointer will be NULL when the attempt to invoke it is made.

    The signature of the function pointer also does not match the signature of the exported function, the exported function returns an int and the function pointer is expecting a double.

    For example:

    typedef int (*func_t)(int, int);
    
    HMODULE hLib = LoadLibrary("test_dll.dll");
    if (hLib)
    {
        func_t pFunction = (func_t)GetProcAddress(hLib, "func");
        if (pFunction)
        {
            Rss = pFunction(1, 2);
        }
        else
        {
            // Check GetLastError() to determine
            // reason for failure.
        }
        FreeLibrary(hLib);
    }
    else
    {
        // Check GetLastError() to determine
        // reason for failure.
    }