编写:
a)文件--打开--新建项目--Win32,右侧Win32项目,填写好项目名称,点击“下一步”,
应用程序类型选择:“DLL(D)”,附加选项:空项目(E),然后完成。
b)编写头文件(edrlib.h):
#ifdef __cplusplus
#define EXPORT extern "C" __declspec (dllexport)
#else
#define EXPORT __declspec (dllexport)
#endif
EXPORT void EdrCenterTextA();
EXPORT void EdrCenterTextW();
EXPORT int IncCounter();
#ifdef UNICODE
#define EdrCenterText EdrCenterTextW
#else
#define EdrCenterText EdrCenterTextA
#endif
注解:
i. 定义 __cplusplus表示是供C++程序中调用。
ii.__declspec (dllexport)表示函数调用方式,此处表示VS2008工程属性调用的默认方式。更改方法:
右击项目--属性--配置属性--C/C++--高级,更改右侧“调用约定”。
c)编写DLL文件(edrlib.cpp):
#include "windows.h"
#include "edrlib.h"
//counter供调用该DLL的所有应用程序共享
#pragma data_seg("shared")
int counter=0;
#pragma comment(linker,"/SECTION:shared,RWS")
int WINAPI DllMain(_In_ HANDLE _HDllHandle, _In_ DWORD _Reason, _In_opt_ LPVOID _Reserved)
{
return TRUE;
}
EXPORT void EdrCenterTextA()
{
MessageBox(NULL,TEXT("调用DLL函数!"),TEXT("ASSIC版本"),MB_OK);
}
EXPORT void EdrCenterTextW()
{
MessageBox(NULL,TEXT("调用DLL函数!"),TEXT("UNICODE版本"),MB_OK);
}
EXPORT int IncCounter()
{
return ++counter;
}
d)编译生成DLL。
调用:
调用DLL有两种方法:静态调用和动态调用.
(一).静态调用其步骤如下:
1.把你的youApp.DLL拷到你目标工程(需调用youApp.DLL的工程)的Debug目录下;
2.把你的youApp.lib拷到你目标工程(需调用youApp.DLL的工程)目录下;
3.把你的youApp.h(包含输出函数的定义)拷到你目标工程(需调用youApp.DLL的工程)目
录下;
4.打开你的目标工程选中工程,选择Visual C++的Project主菜单的Settings菜单;
5.执行第4步后,VC将会弹出一个对话框,在对话框的多页显示控件中选择Link页。然
后在Object/library modules输入框中输入:youApp.lib
6.选择你的目标工程Head Files加入:youApp.h文件;
7.最后在你目标工程(*.cpp,需要调用DLL中的函数)中包含你的:#include "youApp.h"
注:youApp是你DLL的工程名。
2.动态调用其程序如下:
动态调用时只需做静态调用步骤1.
#include <iostream>
#include "windows.h"
using namespace std;
//int WINAPI WinMain(__in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd )
int main(int argc, char** argv)
{
HINSTANCE hDllInst = LoadLibrary(TEXT("model.dll"));
if (!hDllInst){
cout << "load dll error !" << endl;
getchar();
return 1;
}
typedef DWORD (WINAPI *MYFUNC)();
MYFUNC IncCounter = (MYFUNC)GetProcAddress(hDllInst,"IncCounter");
MYFUNC EdrCenterTextA = (MYFUNC)GetProcAddress(hDllInst,"EdrCenterTextA");
MYFUNC EdrCenterTextW = (MYFUNC)GetProcAddress(hDllInst,"EdrCenterTextW");
#ifdef UNICODE
#define EdrCenterText EdrCenterTextW()
#else
#define EdrCenterText EdrCenterTextA()
#endif
if (!IncCounter || !EdrCenterTextA || !EdrCenterTextW){
cout << "find functions error!" << endl;
getchar();
return 1;
}
TCHAR buf[32];
wsprintf(buf,TEXT("now,counter=%d"),IncCounter());
MessageBox(NULL,buf,TEXT("测试dll的用法"),MB_OK);
EdrCenterText;
wsprintf(buf,TEXT("now,counter=%d"),IncCounter());
MessageBox(NULL,buf,TEXT("测试dll的用法"),MB_OK);
FreeLibrary(hDllInst);
return 0;
}
显式(静态)调用:
LIB + DLL + .H,注意.H中dllexport改为dllimport
隐式(动态)调用:
DLL + 函数原型声明,先LoadLibrary,再GetProcAddress(即找到DLL中函数的地址),不用后FreeLibrary
源址:http://blog.csdn.net/breezes2008/article/details/5326861
http://www.cnblogs.com/c1230v/articles/1401448.html
显示调用时博主说把dllexport改成dllimport,我没有按照他说的改,dll工程和调用工程用的是相同的头文件,未作更改,结果也没报错。