简体   繁体   中英

Calling a DLL explicitly

Can anyone tell me why my SimpleTest application does not display "Test"? The DLL loads successfully, I just don't get any console output.

SimpleDLL.cpp

#include "stdafx.h"
#include "SimpleDLL.h"

#include "stdafx.h"
#include <iostream>

int Test()
{
    std::cout << "Test" << std::endl;
    return 0;
}

SimpleDLL.h

#ifndef _DLL_TUTORIAL_H_
#define _DLL_TUTORIAL_H_
#include <iostream>

#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif

DECLDIR int Test();

#endif

SimpleTest.cpp

#include "stdafx.h"
#include <iostream>
#include <windows.h>

typedef int (*TestFunc)();

int main()
{
    TestFunc _TestFunc;
    HINSTANCE hInstLibrary = LoadLibrary( _T("SimpleDLL.dll"));

    if (hInstLibrary)
    {
        _TestFunc = (TestFunc)GetProcAddress(hInstLibrary, "Test");
    }
    else
    {
        std::cout << "DLL Failed To Load!" << std::endl;
    }

    if (_TestFunc)
    {
        _TestFunc();
    }

    FreeLibrary(hInstLibrary);

    return 0;
}

You need to declare extern "C" before __declspec(...) . This is because C++ adds name decoration when you export a C++ function, and you need to declare it as a C function to have the function Test exported as just "Test"

As has been stated by JoesphH you need extern "C" to prevent name mangling. In addition to this do not have either of the following compiler switches specified:

  • Gz __stdcall calling convention: "Test" would be exported as Test@0
  • Gr __fastcall caling convention: "Test" would be exported as @Test@0

Note: I think last symbol is dependent on compiler version but is still not just "Test".

Also, as per my comment check return value from GetProcAddress() and use the value of GetLastError() to obtain reason for failure if NULL was returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM