本文将整理动态链接库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);
(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; }
编译生成
在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; }
(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; }
这种方法中
HMODULE h = LoadLibraryA("Dll1.dll"); func f = (func)GetProcAddress(h, "substract");
必须在生成dll文件时 extern "C";
原文:http://www.cnblogs.com/chen-cqupt/p/4901597.html