在VC2010下新建一个Win32 Project “myDll”,选择工程属性为dll,其它不变。
VC默认生成的文件当中,没有myDll.h文件,手动添加一个。并加入如下代码:
//MyDLL.h
extern "C" _declspec(dllexport) int Max(int a, int b);
extern "C" _declspec(dllexport) int Min(int a, int b);
在myDll.cpp里加入如下代码:
// myDll.cpp : Defines the exported functions for the DLL application.
#include "stdafx.h"
#include "myDll.h"
#include<stdio.h>
#include"MyDll.h"
int Max(int a, int b)
{
if(a>=b)
return a;
else
return b;
}
int Min(int a, int b)
{
if(a>=b)
return b;
else
return a;
}
在Solution下新建一个工程“myDllTest”,在myDllTest.cpp中加入以下代码:
// myDllTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
#include <iostream>
using namespace std;
//#include "..\myDll\myDll.h"
int _tmain(int argc, _TCHAR* argv[])
{
int a, b;
cout << "Please input two numbers:" << endl;
cin >> a >> b;
typedef int (*min)(int, int);
typedef int (*max)(int, int);
HMODULE hModule = LoadLibraryA("myDll.dll");
min Min = (min)GetProcAddress(hModule, "Min");
min Max = (max)GetProcAddress(hModule, "Max");
int min_val = Min(a, b);
int max_val = Max(a, b);
cout << "The max number is " << max_val << endl;
cout << "The min number is " << min_val << endl;
return 0;
}
右击"myDllTest"工程,设置一下“Dependece”--依赖"myDll"工程。
程序运行如下图所示:
说明使用动态链接库成功。>_<