转自:https://www.douban.com/note/366236574/
在非Visual Studio下怎么去编译dll已经在另外一个post中做了描述:http://www.douban.com/note/320768748/。
但是,Visual Studio毕竟是一个非常主流,很难回避的一个编译和整合工具。如何在Visual Studio下,最最最简单的方式声场dll,貌似也没什么好的文档。
优快云上有一篇, http://blog.youkuaiyun.com/ixsea/article/details/6676802,但是这对于入门级快速上手dll的使用,还是略显麻烦。
综上,针对优快云的帖子的方法,我做了一个最简版(vs 2010,2013都兼容):
// ========== 生成dll(不用特意生成h文件,已经整合在一个cpp代码里) =================
// vsDllCreation.cpp : Defines the exported functions for the DLL application.
#include "stdafx.h"
#include <iostream>
#define DLLEXPORT extern "C" __declspec(dllexport) // no illegal codes: [extern "C"] is the fix
DLLEXPORT void printMax(int&,int&); // dll syntax
// dll syntax
// #ifdef CREATEDLL_EXPORTS // illeagal codes
// #define CREATEDLL_API __declspec(dllexport)
// #else
// #define CREATEDLL_API __declspec(dllimport)
// #endif
// CREATEDLL_API void printMax(int&,int&); // dll syntax
void printMax(int& a,int& b)
{
std::cout<<"Among ("<<a<<","<<b<<"), the Max Number is "<<(a>b?a:b)<<"\n";
}
// ========== 调用dll(同样也是单一cpp就足以,设置也不需要改)=================
// vsDllCalling.cpp : Defines the entry point for the console application.
#include "stdafx.h" // for the weird default "_tmain" and "_TCHAR"
#include<Windows.h> // dll syntax
#include<iostream>
//using namespace std; // std is a namespace defined in <iostream>. Here we explictedly use the std::cin to ignore it.
typedef void(*FUNA)(int&,int&); // dll syntax
int _tmain(int argc, _TCHAR* argv[])
{
const _TCHAR* dllName = L"vsDllCreation.dll"; //VS string syntax for 'unicode'
// const char* funName1 = "?printMax@@YAXAAH0@Z"; //VS dll syntax: 'wrong' function name
const char* funName1 = "printMax"; //VS dll syntax
int x(100), y(100), z(100);
HMODULE hDLL = LoadLibrary(dllName);// dll syntax
FUNA fp1 = FUNA(GetProcAddress(hDLL,funName1));// dll syntax
std::cout<<"Input 2 Numbers:";
std::cin>>x>>y;
fp1(x,y);// dll syntax
FreeLibrary(hDLL);// dll syntax
return 0;
}
// ==============================
这分别是两个VS的projects,vsDllCreation和vsDllCalling。其中第二个项目中vsDllCalling需要在其debug或者release(取决于build时在哪种环境)的文件夹中包含第vsDllCreation生成的dll。
Visual Studio生成的dll,其中的function name会被加上一些其他修饰,通过dumpbin可以看出:
// ================
>dumpbin.exe /exports vsDllCreation.dll
----
Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file vsDllCreation.dll
File Type: DLL
Section contains the following exports for vsDllCreation.dll
00000000 characteristics
53B686D7 time date stamp Fri Jul 04 18:49:59 2014
0.00 version
1 ordinal base
1 number of functions
1 number of names
ordinal hint RVA name
1 0 0001116D ?printMax@@YAXAAH0@Z = @ILT+360(?printMax@@YAXAAH0@Z)
Summary
1000 .data
1000 .idata
2000 .rdata
1000 .reloc
1000 .rsrc
6000 .text
10000 .textbss