红山玉龙

导航

[转]一个简单的调用动态库的实例

转自http://blog.csdn.net/lxh1230119/article/details/8071730

 

先创建一个动态库dll工程

工程中添加 dlltest.cpp  dlltest.def  dlltest.h

dlltest.h

[cpp] view plaincopy
 
  1. //dlltest.h  
  2. extern __declspec(dllexport) int FuncTest();  

dlltest.cpp

[cpp] view plaincopy
 
  1. //dlltest.cpp  
  2. __declspec(dllexport) int FuncTest(int a )  
  3. {  
  4.     if (a = 1)  
  5.     {  
  6.         return 100;  
  7.     }  
  8. }  

dlltest.def

[cpp] view plaincopy
 
  1. LIBRARY "testmydll"  
  2. EXPORTS  
  3.     FuncTest  

 

 

编译后生成dlltest.dll  dlltest.lib

再新建一个Win32控制台工程用来调用dlltest.dll  

将dlltest.dll拷贝到Win32的Debug目录下面

Win32项目中dll.cpp文件如下

[cpp] view plaincopy
 
  1. #include <iostream>     
  2. #include "string"     
  3. #include <stdio.h>    
  4. #include <windows.h>  
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     typedef int (*HFUNC)(int a );  
  10.     HINSTANCE hDLL = LoadLibrary("testmydll.dll");  
  11.     if (hDLL)  
  12.     {  
  13.         HFUNC hFun = (HFUNC)GetProcAddress(hDLL,"FuncTest");  
  14.         if (hFun)  
  15.         {  
  16.             int a =1;  
  17.             int b = hFun(a);  
  18.             printf("%d\n",b);  
  19.         }  
  20.     }  
  21.   
  22. }  


 

编译执行则调用了dlltest.dll 打印出100

 

 

 

如果是调用 dlltest.lib的话,就要将dlltest.lib拷贝到工程目录下(Debug上一级),编译的时候就直接链接了,另外还要把头文件 dlltest.h加到工程中

Win32项目中dll.cpp中的代码如下

[cpp] view plaincopy
 
  1. #include <iostream>     
  2. #include "string"     
  3. #include <stdio.h>    
  4. #include <windows.h>  
  5. #include "dlltest.h"  
  6. using namespace std;  
  7. #pragma comment(lib,"testmydll.lib")  
  8. __declspec(dllimport) int FuncTest(int a );  
  9. int main()  
  10. {  
  11.     int b = FuncTest(1);  
  12.     printf("%d\n",b);  
  13.     return 0;  
  14. }  


编译执行打印出100

posted on 2015-07-17 17:28  红山玉龙  阅读(130)  评论(0)    收藏  举报