zl程序教程

您现在的位置是:首页 >  后端

当前栏目

vs2008 C++创建和调用标准DLL

C++标准 创建 调用 dll vs2008
2023-09-11 14:16:45 时间
为了共享代码,需要生成标准的dll,本文将介绍在vs2008 C++生成及调用dll。

一、生成DLL

    生成一个名为FunDll的dll文件,对外函数为addl。

   step1:vs2008 环境下,文件-->新建项目,选择visual c++,在选择 “Win32 项目”,键入项目名称,如 FunDll。如图:

   

点击下一步,勾选“DLL”和“导出空符号”,单击“完成”

  

step 2,编写功能函数

   执行完step1步骤后,在FunDll.h 和FunDll.cpp中会生成一些实例代码,先把这些注释掉,同时修改FunDll.h中的预处理宏定义为:

#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:

[cpp]  view plain copy
  1. // 下列 ifdef 块是创建使从 DLL 导出更简单的  
  2. // 宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 FUNDLL_EXPORTS  
  3. // 符号编译的。在使用此 DLL   
  4. // 任何其他项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将  
  5. // FUNDLL_API 函数视为是从 DLL 导入的,而此 DLL 则将用此宏定义的  
  6. // 符号视为是被导出的。  
  7.   
  8. #ifdef FUNDLL_EXPORTS  
  9. #define FUNDLL_API extern "C" __declspec(dllexport)  
  10. #else  
  11. #define FUNDLL_API extern "C" __declspec(dllexport)  
  12. #endif  
  13. FUNDLL_API int _stdcall add(int plus1,int plus2);  

FunDll.cpp

[cpp]  view plain copy
  1. #include "stdafx.h"  
  2. #include "FunDll.h"  
  3.   
  4. int _stdcall add(int plus1,int plus2)  
  5.  
  6.     int ret  
  7.     ret=plus1+plus2;  
  8.     return ret;  
  9.  

step3:添加 FunDll.def,修改内容为

[cpp]  view plain copy
  1. LIBRARY "FunDll"  
  2. EXPORTS  
  3.     add  


step 4,发布FunDll.dll文件

二,调用FunDll.dll

step1,新建C++控制台程序,项目名称为TestDll。

修改TestDll.cpp的代码为:

[cpp]  view plain copy
  1. // TestDll.cpp 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include   
  6. #include   
  7. #include   
  8.   
  9. //定义MYPROC为指向一个返回值为int型的函数的指针  
  10. typedef int (__stdcall *MYPROC)(int a,int b);  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13.     
  14.     HINSTANCE hinstLib;  
  15.     MYPROC ProcAdd;  
  16.     int val1,val2,res;  
  17.     val1=4;  
  18.     val2=5;  
  19.     // Get handle to the DLL module.  
  20.     hinstLib LoadLibrary(L"FunDll.dll");   
  21.   
  22.     // If the handle is valid, try to get the function address.  
  23.     if (hinstLib != NULL)   
  24.       
  25.         ProcAdd (MYPROC) GetProcAddress(hinstLib, "add");   
  26.         res=(ProcAdd)(val1,val2);  
  27.         printf("%d\n",res);  
  28.      
  29.         return 0;  
  30.  


step2,把FunDll拷贝至TestDll项目文件夹下。

step3,运行,测试通过。