显式调用一个DLL

谁能告诉我为什么我的SimpleTest应用程序不显示“testing”? 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”将被导出为Test@0
  • Gr __fastcall调用约定:“Test”将被导出为@Test@0

注意:我认为最后一个符号依赖于编译器版本,但仍然不仅仅是“测试”。

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