动态链接库应用举例

既然写了静态链接库,就顺带把动态链接库也学习下。

创建一个动态链接库工程,名称为ConvertDynamicLib

在cpp文件中写入下面的代码

 1 #include "stdafx.h"
 2 #include <stdlib.h>
 3 #include <windows.h>
 4 #include <stdio.h>
 5 
 6 BOOL APIENTRY DllMain( HANDLE hModule, 
 7                        DWORD  ul_reason_for_call, 
 8                        LPVOID lpReserved
 9                      )
10 {
11     return TRUE;
12 }
13 
14 __declspec(dllexport) void BinToDec(char* szDecOutput,char* szBinInput)
15 {
16     int nDecimal=0;
17     int Len=lstrlen(szBinInput);
18     for (int i=0;i<Len;i++)
19     {
20         char h = szBinInput[Len-1-i];                                    
21         char str[1];
22         str[0]=h;
23         int j = atoi(str);                                              
24         for (int k=0;k<i;k++)                                            
25         {
26             j = j*2;
27         }
28         nDecimal = nDecimal+j;    
29     }
30     sprintf(szDecOutput,"%d",nDecimal);
31 }
32 
33 __declspec(dllexport) void OctToDec(char* szDecOutput,char* szOctInput)
34 {
35     int nLenth = lstrlen(szOctInput);
36     
37     
38     int nDecimal = 0;
39     for(int i=0;i<nLenth;i++)
40     {
41         char h = szOctInput[nLenth-1-i];
42         char str[1];
43         str[0] = h;
44         int j = atoi(str);
45         for(int k=0;k<i;k++)
46         {
47             j=j*8;
48         }
49         nDecimal += j;
50     }
51     sprintf(szDecOutput,"%d",nDecimal);
52 }
__declspec(dllexport)在这里的意思是把后面的函数作为导出函数,以便可以在其它程序中使用

编译

========================================

新建一个控制台程序,将动态链接库的dll文件和lib文件拷贝到当前的工程目录中

lib文件为编译时需要,dll为运行时需要

 1 #include "stdafx.h"
 2 #include <stdio.h>
 3 
 4 #pragma comment(lib,"ConvertDynamicLib.lib")
 5 void BinToDec(char* szDecOutput,char* szBinInput);
 6 void OctToDec(char* szDecOutput,char* szOctInput);
 7 
 8 
 9 int main(int argc, char* argv[])
10 {
11     char tk[256]="";
12     char inputsz[256]="1010101001";
13     BinToDec(tk,inputsz);
14     printf("%s\n",tk);
15     return 0;
16 }

看代码就知道,添加lib文件,声明dll中的函数

然后在main函数中调用函数。

原文地址:https://www.cnblogs.com/tk091/p/TK.html