上一篇说到如何创建一个dll 本篇讲一下如何调用dll。
1.创建一个程序来调用我们的dll
a.new project 选择 window console
b.第二步选择next 第三步:application type:console application 点击finish
c.工程创建完毕,里面有三个文件stdafx.h stdafx.cpp dll_demo_testcase.cpp 。
2. dll调用方法介绍
我们要调用dll_demo.dll,有两种方法:
(1)隐式连接 (2)显示链接
后面我们一一道来
3.隐式连接 调用dll
a.在工程文件夹新建一个同级common目录保存生成的dll和lib
b.拷贝生成的dll_demo.dll 和 dll_demo.h到当前工程目录
c.在工程配置linker-》Additional Library Directories中添加common用于引用lib
d. stdafx.h添加dll_demo.h头文件和对lib包含
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows.
#endif
#include <stdio.h>
#include <tchar.h>
#include "my_dll.h"
#pragma comment(lib, "dll_demo")
// TODO: reference additional headers your program requires here
e. 回到 dll_demo_testcase.cpp 中的代码,这时候我们可以再 _tmain中添加我们的测试代码
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
SayHello();
std::cout<< Add(5, 6);
system("pause");
return 0;
}
f. F5执行 会在控制台打印信息
4.显示连接调用
显示连接就是利用windows 的API LoadLibrary (LoadLibraryEx) 来动态加载dll,不需要头文件,只需要添加相应代码
// my_dll_testcase.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
//定义函数指针
typedef int (*AddFunc)(int,int);
typedef void (*HelloFunc)();
int _tmain(int argc, _TCHAR* argv[])
{
AddFunc _AddFunc;
HelloFunc _HelloFunc;
HINSTANCE hInstLibrary = LoadLibrary(_T("dll_demo.dll"));
if (hInstLibrary == NULL)
{
FreeLibrary(hInstLibrary);
}
_AddFunc = (AddFunc)GetProcAddress(hInstLibrary, "Add");
_HelloFunc = (HelloFunc)GetProcAddress(hInstLibrary, "SayHello");
if ((_AddFunc == NULL) || (_HelloFunc == NULL))
{
FreeLibrary(hInstLibrary);
}
std::cout << _AddFunc(8, 10) << std::endl;
_HelloFunc();
std::cin.get();
//使用完毕一定要释放
FreeLibrary(hInstLibrary);
return (1);
}