为了共享代码,需要生成标准的dll,本文将介绍在vs2008 C++生成及调用dll。
一、生成DLL
点击下一步,勾选“DLL”和“导出空符号”,单击“完成”
step 2,编写功能函数
#ifdef FUNDLL_EXPORTS
#define FUNDLL_API extern "C" __declspec(dllexport)
#else
#define FUNDLL_API extern "C" __declspec(dllexport)
#endif
在FunDll.h中声明add函数,在FunDll.cpp中实现该函数。修改完后代码如下:
FunDll.h:
- //
下列 ifdef 块是创建使从 DLL 导出更简单的 - //
宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 FUNDLL_EXPORTS - //
符号编译的。在使用此 DLL 的 - //
任何其他项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将 - //
FUNDLL_API 函数视为是从 DLL 导入的,而此 DLL 则将用此宏定义的 - //
符号视为是被导出的。 -
- #ifdef
FUNDLL_EXPORTS - #define
FUNDLL_API extern "C" __declspec(dllexport) - #else
- #define
FUNDLL_API extern "C" __declspec(dllexport) - #endif
- FUNDLL_API
int _stdcall add(int plus1,int plus2);
FunDll.cpp
- #include
"stdafx.h" - #include
"FunDll.h" -
- int
_stdcall add(int plus1,int plus2) - {
-
int ret ; -
ret=plus1+plus2; -
return ret; - }
step3:添加 FunDll.def,修改内容为
- LIBRARY
"FunDll" - EXPORTS
-
add
step 4,发布FunDll.dll文件
二,调用FunDll.dll
step1,新建C++控制台程序,项目名称为TestDll。
修改TestDll.cpp的代码为:
- //
TestDll.cpp : 定义控制台应用程序的入口点。 - //
-
- #include
"stdafx.h" - #include
- #include
- #include
-
- //定义MYPROC为指向一个返回值为int型的函数的指针
- typedef
int (__stdcall *MYPROC)(int a,int b); -
- int
_tmain(int argc, _TCHAR* argv[]) - {
-
HINSTANCE hinstLib; -
MYPROC ProcAdd; -
int val1,val2,res; -
val1=4; -
val2=5; -
// Get a handle to the DLL module. -
hinstLib = LoadLibrary(L"FunDll.dll"); -
-
// If the handle is valid, try to get the function address. -
if (hinstLib != NULL) -
{ -
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "add"); -
res=(ProcAdd)(val1,val2); -
printf("%d\n",res); -
} -
return 0; - }
step2,把FunDll拷贝至TestDll项目文件夹下。
step3,运行,测试通过。