首页 > 其他 > 详细

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

时间:2015-10-22 18:52:14      阅读:229      评论:0      收藏:0      [点我收藏+]

本文将整理动态链接库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";

 

   

 

 

 

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

原文:http://www.cnblogs.com/chen-cqupt/p/4901597.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!