21window_21_Dynamic_library动态库

21window_21_Dynamic_library动态库

DLL创建
//1.1 创建DLL的项目
//1.2 增加动态库函数
__declspec( dllexport ) //C++导出方式
int Dll_Add( int nAdd1, int nAdd2 )
{
return nAdd1 + nAdd2;
}
 
//导出函数关键字__declspec( dllexport )
extern "C" __declspec( dllexport ) //C导出方式
int Dll_Sub( int nSub1, int nSub2 )
{
return nSub1 - nSub2;
}
//1.3 导出动态库函数
 
//DEF的导出方式
int Dll_Mul( int nMul1, int nMul2 )
{
return nMul1 * nMul2;
}

DLL使用
    隐式调用
#include <iostream>
using namespace std;
 
//第2.1.1步 导入 lib
#pragma comment(lib,"../debug/windows_21_Library_DLL_test.lib")
 
//第2.1.2步 定义函数原型
int Dll_Add( int nAdd1, int nAdd2 );
extern "C"/*如果不加这个会出错*/ int Dll_Sub( int nSub1, int nSub2 );
 
//DEF导出定义函数原型
int Dll_Mul( int nMul1, int nMul2 );
 
int main( )
{
//第2.1.3步 使用函数
int nAdd = Dll_Add( 100, 100 );
int nSub = Dll_Sub( 100, 100 );
int nMul = Dll_Mul( 100, 100 );
 
cout << nAdd << endl << nSub << endl << nMul << endl;
}

DEF文件
LIBRARY
EXPORTS
Dll_Mul @1

    显式调用
// windows_21_Library_use_DLL_Invoke.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include <windows.h>
 
 
//2.2.2 定义函数指针,在开发工程中,一般都是大写
typedef int( *DLL_ADD )( int nAdd1, int nAdd2 );
typedef int( *DLL_SUB )( int nSub1, int nSub2 );
typedef int( *DLL_MUL )( int nMul1, int nMul2 );
 
 
void UseDll( )
{
//2.2.1 加载动态库,使用LoadLibrary,HMODULE = HINSTANCE
HMODULE hDll = (HMODULE)LoadLibrary( "windows_21_Library_DLL_test.dll" );
if (hDll == NULL)
{
printf( "Load Failed\n" );
return;
}
printf( "hDll handle: %p\n", hDll );
//2.2.2 定义函数指针变量
DLL_ADD Dll_Add = NULL;
DLL_SUB Dll_Sub = NULL;
DLL_MUL Dll_Mul = NULL;
 
//2.2.3 获取函数地址 GetProcAddress
Dll_Add = (DLL_ADD)GetProcAddress( hDll, "Dll_Add" ); //取得Dll_Add函数地址转换成DLL_ADD类型
printf( "Dll_Add handle: %p\n", Dll_Add );
Dll_Sub = (DLL_SUB)GetProcAddress( hDll, "Dll_Sub" );
printf( "Dll_Sub handle: %p\n", Dll_Sub );
Dll_Mul = (DLL_MUL)GetProcAddress( hDll, "Dll_Mul" );
printf( "Dll_Mul handle: %p\n", Dll_Mul );
 
if (!(Dll_Add && Dll_Sub && Dll_Mul))
{
printf( "Get function failed\n" );
}
//2.2.4 使用函数
//由于 Dll_Add函数DLL文件里使用的是CPP方式导出,无法得到正确的函数名,所以在这里无法使用
int nSub = Dll_Sub( 100, 100 );
int nMul = Dll_Mul( 100, 100 );
printf( "nSub:%d\n", nSub );
printf( "nMul:%d\n", nMul );
 
//2.2.5 释放动态库,看样子有加载就有释放的预言就又实现了
FreeLibrary( hDll );
}
int _tmain(int argc, _TCHAR* argv[])
{
UseDll( );
return 0;
}




posted @ 2016-06-10 08:32  -刀狂剑痴-  阅读(165)  评论(0编辑  收藏  举报