显式调用DLL

pin*_*ngu 1 c++ windows dll visual-studio-2008

谁能告诉我为什么我的SimpleTest应用程序不显示"测试"?DLL加载成功,我只是没有得到任何控制台输出.

SimpleDLL.cpp

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

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

int Test()
{
    std::cout << "Test" << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*phH 6

需要声明extern "C"之前__declspec(...).这是因为C++在导出C++函数时添加了名称修饰,并且需要将其声明为C函数以将函数Test导出为"Test"