http://blog.csdn.net/yangywyangyw/article/details/5967105

链接库文件TestDLL.h

 

 

  1. #pragma once  
  2.   
  3. extern "c" int _declspec(dllexport)add(int ,int);//注意这里不能是_stdcall,否则编译出错,具体原因我也不知呀!  

 

链接库文件TestDLL.cpp

 

  1. #include "TestDLL.h"  
  2.   
  3. int add(int a,int b)  
  4. {  
  5.    return a+b;  
  6. }  

 

 

测试链接文件testlink.cpp

 

  1. #include<iostream>  
  2. #include<windows.h>  
  3.   
  4. typedef (*inport)(int ,int );  
  5.   
  6. int main()  
  7. {  
  8.   HINSTANCE hdll; //dll句柄  
  9.   inport addnew; //新函数指针  
  10.     
  11.   hdll=LoadLibrary(".../TestDLL.dll");  
  12.     
  13.   if(hdll==NULL)  
  14.   {  
  15.     std::cout<<"load dll error!"<<std::endl;  
  16.   }  
  17.     
  18.   addnew=(inport)GetProcAddress(hdll,"add");  
  19.   
  20.   std::cout<<addnew(100,60)<<std::endl;  
  21.   
  22.   return 0;  
  23. }  

 

 

输出结果:

 

160

 

在TestDLL中再创建DLLMAIN函数如下:

 

  1. #include <iostream>  
  2. #include <windows.h>  
  3.   
  4. using namespace std;  
  5.   
  6. bool APIENTRY DllMain(HANDLE hMoudole,DWORD ul_reason_for_call,LPVOID lpReserved)  
  7. {  
  8.     switch(ul_reason_for_call)  
  9.     {  
  10.     case DLL_PROCESS_ATTACH:  
  11.         cout<<"process attach of dll"<<endl;  
  12.         break;  
  13.     case DLL_THREAD_ATTACH:  
  14.         cout<<"thread attach of dll"<<endl;  
  15.         break;  
  16.     case DLL_THREAD_DETACH:  
  17.         cout<<"thread detach of dll"<<endl;  
  18.         break;  
  19.     case DLL_PROCESS_DETACH:  
  20.         cout<<"process detach of dll"<<endl;  
  21.     }  
  22.     return true;  
  23. }  

 

 

则输出结果为:

 

process attach of dll
160
process detach of dll

 

以上是动态调用(程序在需要的时候再加载所需要的DLL,此种用法比较灵活)

 

再来看下静态调用,与动态调用不同的是,此种调用在程序编译时就将DLL的加载信息LIB编译进EXE中,当应用程序需要时便从相应的LIB文件中取得DLL的信息来加载DLL,通过符号名来实现对DLL函数的动态链接,与调用内部函数没有区别!

将调用函数testlink.cpp改写成这样:

 

  1. #include <iostream>  
  2. #include <windows.h>  
  3.   
  4. #include "F:/学习资料/C++编程/TestDLL/TestDLL.h"  
  5. #pragma comment(lib,"F://学习资料//C++编程//TestDLL//Debug//TestDLL.lib")  
  6.   
  7. extern "C" int _declspec(dllimport)add(int a,int b);  
  8.   
  9. int main()  
  10. {  
  11.     std::cout<<add(100,60)<<std::endl;  
  12.   
  13.     return 0;  
  14. }  

 

预期输出结果为

process attach of dll
160
process detach of dll

 

但编译时出现1个警告:inconsistent dll linkage.  dllexport assumed. 未出现错误

而执行时提示:无法启动应用程序,因为计算机中丢失TestDLL.dll

具体原因未知,请看原文

Copyright © 2024 无忧consume
Powered by .NET 8.0 on Kubernetes