动态链接库DLL封装及调用方法

本文将整理动态链接库dll的封装方法及调用的方法。(以VS2010为开发平台)

1,动态链接库dll的封装方法

封装步骤:

(1),在VS2010中新建一个win32->dll工程;

(2),新建一个头文件Dll1.h

#ifndef DLL1_API
#define DLL1_API extern "C" _declspec (dllimport)
#endif

DLL1_API int add(int a , int b);
DLL1_API int substract(int a ,int b);
View Code

(3),新建一个cpp文件Dll1.cpp

// Dll1.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"

#define DLL1_API extern "C" _declspec(dllexport)

#include "Dll1.h"

 int add(int a , int b)
{
    return a+b;    
}

int substract(int a , int b)
{
    return a-b;
}
View Code

编译生成

在debug文件夹中会生成相应的DLL及LIB文件:*.dll   *.lib

2,动态链接库dll的调用方法

新建一个win32的控制台应用程序dlltest

(1)调用方法一:

       a,拷贝dll的封装编译生成的*dll,*.lib,Dll1.h文件到dlltest工程目录下;

       b,在cpp文件中添加如下的代码:

// dlltest2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include <Windows.h>
#include "Dll1.h"
#pragma  comment (lib,"Dll1.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    int a = 10;
    int b =2;
    cout<<add(a,b)<<endl;;
    cout<<substract(a,b);
    system("pause");
    return 0;
}
View Code

 

 (2)调用方法二:

    备注: 方法二和方法一相比 , 不用添加*.h头文件 和代码#pragma  comment (lib,"Dll1.lib")

// dlltest2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include <Windows.h>
//#include "Dll1.h"
//#pragma  comment (lib,"Dll1.lib")
using namespace std;
typedef int (*func)(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE h = LoadLibraryA("Dll1.dll");
    func f = (func)GetProcAddress(h, "substract");
    cout<<f(10,2);

    /*int a = 10;
    int b =2;
    cout<<add(a,b)<<endl;;
    cout<<substract(a,b);*/
    system("pause");
    return 0;
}
View Code

这种方法中

HMODULE h = LoadLibraryA("Dll1.dll");
func f = (func)GetProcAddress(h, "substract");

必须在生成dll文件时 extern "C";

 

   

 

 

 

转载于:https://www.cnblogs.com/chen-cqupt/p/4901597.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值