DLL两种常用的创建和引用方法

Dll调用有很多方法,这里总结两种比较常用的

1)会提供三个文件的.lib.dll.h,而且采用标准调用的方式

          头文件dll1.h

#ifdef DLL1_API
#else
#define DLL1_API extern"C" _declspec(dllimport)
#endif

DLL1_API int _stdcall Test(int a,int b);


  源文件
dll1.cpp

#include"dll1.h"
#define DLL1_API extern "C" _declspec(dllexport)
 
DLL1_API  int _stdcall Test(int a,int b)
{
    return a+b;
 
}



模块文件 dll1.def

LIBRARY dll1
EXPORTS
  Test
 

 

新建一个测试工程,加入头文件dll1.h

lib库增加到工程内,属性-链接器-输入-添加依赖项--加入dll1.lib

dll文件放入工程内,项目-属性-c++ -附加包含目录

#include "stdafx.h"
#include "dll1.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
      int a=1,b=3;
      cout<<"c= "<< Test(1,3)<<endl;
 
      system("pause");
      return 0;
}


(2)如果项目需要的动态链接库很多,但是也不是每个链接库内的函数都用到,使用上述的方式会占用很大内存,因此使用动态加载的方法

 

  新建一个测试工程2,将dll1.dll与.exe放入同一个文件夹内

#include "stdafx.h"
#include<iostream>
#include<Windows.h>
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
      HMODULE  hDLL;//模块句柄
      hDLL=LoadLibrary(_T("dll1.dll"));//加载dll
      typedef int(_stdcall *ADDPROC)(int a,int b);
      ADDPROC test = (ADDPROC )GetProcAddress(hDLL,"Test");//获取地址
      if(!test)
     {
           cout<<"获取函数地址失败"<<endl;
     }
    else
     {
           cout<<"c is : "<<test(2,3) <<endl;//调用函数
     }
     FreeLibrary(hDLL);//释放资源
     system("pause");
     return 0;
}


 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值