创建DLL:
先声明导出函数:使用__declspec(dllexport)
#include"DLLSample.h"
#ifndef _DLL_SAMPLE_H #define _DLL_SAMPLE_H //如果定义了C++编译器,那么声明为C链接方式, //否则编译后的函数名为?TestDLL@@YAXXZ,而并不是TestDLL //则不能通过GetProcAddress()获取函数名,因为无法知道DLL编译后的函数名 //******* //如果编译时用的C方式导出函数,则在导入时也要使用C方式(在应用程序#define _cplusplus) //不然会找不到函数 //******* #ifdef _cplusplus extern "C" { #endif //通过宏来控制是导入还是导出 #ifdef _DLL_SAMPLE #define DLL_SAMPLE_API __declspec(dllexport) #else #define DLL_SAMPLE_API __declspec(dllimport) #endif //导入导出函数声明 DLL_SAMPLE_API void TestDLL(int); //导入导出变量声明 DLL_SAMPLE_API extern int DLLData; // 导出/导入类声明 class DLL_SAMPLE_API DLLClass { public: DLLClass(); void Show(); int Data; }; #undef DLL_SAMPLE_API #ifdef _cplusplus } #endif #endif
编写DLL实现
2014_4_9_DLL.dll
#include<objbase.h> #define _DLL_SAMPLE //声明是导出 #define _cplusplus //声明为C编译方式 #ifndef _DLL_SAMPLE_H #include "DLLSample.h" #endif #include "stdio.h" int DLLData; //APIENTRY声明DLL函数入口点 BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DLLData = 456; break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } void TestDLL(int arg) { printf("DLL output arg %d\n", arg); } DLLClass::DLLClass() { Data = 999; } void DLLClass::Show() { printf("DLLClass Show()!\n"); }
显示调用DLL
#include<iostream> #include<Windows.h> using namespace std; typedef void (*LPFUNC)(int); int main() { LPFUNC testFunc; int myData; HINSTANCE hins = ::LoadLibrary("C:\\Users\\Administrator\\Documents\\Visual Studio 2012\\Projects\\2014_4_9_DLL\\Debug\\2014_4_9_DLL.dll"); if(NULL != hins) { cout<<"dll is loaded!"<<endl; } //testFunc = (LPFUNC)GetProcAddress(hins,MAKEINTRESOURCE(1)); testFunc = (LPFUNC)GetProcAddress(hins,"TestDLL"); if(NULL == testFunc) FreeLibrary(hins); else testFunc(123); myData = *(int*)GetProcAddress(hins,"DLLData"); cout<<"get the data:"<<myData<<endl; FreeLibrary(hins); system("pause"); return 0; }
隐式调用DLL
配置路径
Include:C:\Users\Administrator\Documents\Visual Studio 2012\Projects\2014_4_9_DLL\2014_4_9_DLL
Lib:C:\Users\Administrator\Documents\Visual Studio 2012\Projects\2014_4_9_DLL\Debug;
#include<iostream> #define _cplusplus //如果DLL用C方式编译函数,要定义此宏 PS: 为什么?? #include"DLLSample.h" using namespace std; #pragma comment(lib,"2014_4_9_DLL.lib") int main() { DLLClass dc; dc.Show(); cout<<"dc.Data:"<<dc.Data<<endl; TestDLL(345); cout<<"DLLData:"<<DLLData<<endl; system("pause"); return 0; }