显式调用DLL
Calling a DLL explicitly
有人能告诉我为什么我的SimpleTest应用程序不显示"Test"吗?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
导出为"测试"
extern "C"
来防止名称篡改。除此之外,没有指定以下任何一个编译器开关:
- Gz
__stdcall
调用约定:"Test"将导出为Test@0
- Gr
__fastcall
缩放约定:"Test"将导出为@Test@0
注意:我认为最后一个符号取决于编译器版本,但仍然不仅仅是"测试"
此外,根据我的注释,检查来自GetProcAddress()
的返回值,并使用GetLastError()
的值来获取返回NULL时失败的原因。
相关文章:
- 如何安全地从 DLL 调用返回对象
- C++结构到德尔福记录dll调用
- 从 C#-DLL 调用函数的 C++ 失败
- 可视C++:XGBoost 从 DLL 调用时不起作用
- Unity3D的OpenCV dll调用导致FPS下降
- 创建一个C++DLL以从C#DLL调用方法
- 从 dll 调用 opencv 垫到 Windows 表单,图像出现故障
- 努力使用 C# 从本机 DLL 调用该方法
- WinAPI - GetLastError 在通过 COM ATL DLL 调用时始终返回 0
- 必须使用C DLL调用C#.NET方法
- 如何直接从 pdfium.dll 调用 v8 函数
- 为什么从 DLL 调用类方法需要虚拟说明符?
- VBA 中的多个 DLL 调用
- 挂钩VirtualAlloc在系统DLL调用时返回NULLPTR
- 无法从 C DLL 调用该函数
- DLL 调用涉及 strncpy() 的方法
- JNA从DLL调用C++对象-java.lang.IollegalArgumentException:Structure
- 德尔福动态DLL调用中的奇怪行为
- 从非托管 DLL 调用 UWP api
- boost::从 DLL 调用时日志格式不起作用