VS2010下Dll的二次封装以及显示调用

1 篇文章 0 订阅

需要用到二次封装,其实很简单,不过在第二个dll调用第一个dll的方法而已。 
笔记下以免忘了。 
//dll1.h

#ifndef _dll1_h
#define _dll1_h
#define MYDLL extern "C" _declspec (dllexport)
MYDLL int add(int x,int y);
#endif //_dll1_h

//dll1.cpp

#include "stdafx.h"
#include "dll1.h"
using namespace std;
int add(int x,int y)
{
    return x+y; 
}

//dll2.h

#include "dll1.h"
//#pragma comment(lib,"MyDll.lib")
#ifndef _dll2_h
#define _dll2_h
#define MYDLL extern "C" _declspec (dllexport)
MYDLL int add_10(int x,int y);
#endif //_dll2_h

//dll2.cpp

#include "stdafx.h"
#include "dll2.h"

using namespace std;

int add_10(int x,int y)
{
    return add(x,y)+10; <pre name="code" class="cpp">}

 
  

使用DLL

#include "stdafx.h"
#include<iostream>
//#include "dll1.h"
//#pragma comment(lib,"MyDll.lib")
#include "dll2.h"
#pragma comment(lib,"MyDll1.lib")

using namespace std;
int main()
{
//    cout<<"dll1_add:"<<add(3+6)<<endl;
    cout<<"dll2_add:"<<add_10(3,6)<<endl;
    getchar();	
}

Dll的显式链接调用。

#include "stdafx.h"
#include <iostream>
#include "windows.h"
using namespace std;

typedef int (CALLBACK* LPFun)(int,int);//函数指针

void callDll()
{ 
    HINSTANCE hDLL; // Handle to DLL
    LPFun pFun;     // Function pointer
    int nParam1,nParam2, nReturnVal;

    hDLL = LoadLibrary("MyDLL");//导入动态链接库
    if (hDLL != NULL)
    {
       pFun = (LPFun)GetProcAddress(hDLL,"DLLFunc1");//获取函数指针,GetProcAddress("动态链接库名称","函数名称")
       if (!pFun){
          // handle the error
          FreeLibrary(hDLL);//释放动态链接库
          return;
       }else{
          // call the function
          nReturnVal = pFun(nParam1, nParam2);
       }
    }
}

1.声明头文件<windows.h>,说明我想用windows32方法来加载和卸载DLL

2.然后用typedef定义一个指针函数类型.typedef  void(*fun) //这个指针类型,要和你调用的函数类型和参数保持一致,记住,是指针参数就是(int *,int)

3.定一个句柄实例,用来取DLL的实例地址。HINSTANCE hdll;

格式为hdll=LoadLibrary(“DLL地址”);这里字符串类型是LPSTR,当是unicode字符集的时候会不行,因此要在配置-属性-常规里面把默认字符集“unicode”改成支持多字符扩展即可。

4.取的地址要判断,返回的句柄是否为空,如果为无效句柄,那么要释放加载DLL所占用的内存。

FreeLibrary(hdll);

5.然后定义一个函数指针,用来获取你要用的函数地址,这个咋用呢?

先是定一个函数指针 fun FUN;然后通过GetProcAdress来获取函数的地址,这个函数参数是什么呢?

参数是DLL的句柄和你要调用的函数名:比如:FUN=(fun)GetProcAdress(hdll,"sum");

这里也要判断要函数指针是否为空,如果没取到要求的函数,那么要释放句柄

FreeLibrary(hdll);

6.然后通过函数指针来调用函数。

FUN(int *p,int count);这里不能用函数名来使用函数,因为这个DLL本身不是当前CPP的一部分,而是通过windows去调用.没有在这个工程里声明或者定义,而是暴露出一个头,要指针获取他的地址,通过指针来调用.

最后调用结束后,就释放句柄

FreeLibrary(hdll);

这里只是通过动态加载没有涉及到静态的。这个在后续会学习。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值