繁体   English   中英

显式调用DLL

[英]Calling a DLL explicitly

谁能告诉我为什么我的SimpleTest应用程序不显示“测试”? DLL加载成功,但没有任何控制台输出。

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;
}

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

正如JoesphH所说的那样,您需要使用extern "C"来防止名称篡改。 除此之外,没有指定以下任何一个编译器开关:

  • Gz __stdcall调用约定:“测试”将导出为Test@0
  • Gr __fastcall校准惯例:“测试”将导出为@Test@0

注意:我认为最后一个符号取决于编译器版本,但仍然不只是“ Test”。

此外,根据我的评论,检查从GetProcAddress()返回的值,并使用GetLastError()的值来获取失败(如果返回NULL GetLastError()原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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