1 \ 生成dll文件
// MyDll.h: interface for the MyDll class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_MYDLL_H__E6C7930C_99AF_46AF_B08E_42EDB1680395__INCLUDED_)
#define AFX_MYDLL_H__E6C7930C_99AF_46AF_B08E_42EDB1680395__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
extern "C" __declspec(dllexport) __stdcall int Plus(int x,int y);
extern "C" __declspec(dllexport) __stdcall int Sub(int x,int y);
extern "C" __declspec(dllexport) __stdcall int Mul(int x,int y);
extern "C" __declspec(dllexport) __stdcall int Div(int x,int y);
#endif // !defined(AFX_MYDLL_H__E6C7930C_99AF_46AF_B08E_42EDB1680395__INCLUDED_)
myDll.cpp
// MyDll.cpp: implementation of the MyDll class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MyDll.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
int __stdcall Plus(int x,int y)
{
return x+y;
}
int __stdcall Sub(int x,int y)
{
return x-y;
}
int __stdcall Mul(int x,int y)
{
return x*y;
}
int __stdcall Div(int x,int y)
{
return x/y;
}
2\ 使用dll动态链接库
两种使用方法
a - 显示调用, __declspec(dllimport)
b- 隐示调用, 函数指针的方法
测试代码
// 20171111_01.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#pragma comment(lib,"TestDll.lib")
/*
extern "C" __declspec(dllimport) __stdcall Plus(int x,int y);
extern "C" __declspec(dllimport) __stdcall Sub(int x,int y);
extern "C" __declspec(dllimport) __stdcall Mul(int x,int y);
extern "C" __declspec(dllimport) __stdcall Div(int x,int y);
*/
typedef int (__stdcall *lpPlus) (int x,int y);
typedef int (__stdcall *lpSub) (int x,int y);
typedef int (__stdcall *lpMul) (int x,int y);
typedef int (__stdcall *lpDiv) (int x,int y);
int main(int argc, char* argv[])
{
lpPlus myPlus;
lpSub mySub;
lpMul myMul;
lpDiv myDiv;
HINSTANCE hModule = LoadLibrary("TestDll.dll");
myPlus = (lpPlus)GetProcAddress(hModule,"_Plus@8");
mySub = (lpPlus)GetProcAddress(hModule,"_Sub@8");
myMul = (lpPlus)GetProcAddress(hModule,"_Mul@8");
myDiv = (lpPlus)GetProcAddress(hModule,"_Div@8");
//printf("Hello World!\n");
int x= mySub(101,11);
printf("%d \n",x);
FreeLibrary(hModule);
return 0;
}
按照序号导入的代码案例
//隐藏了函数名称,在应用程序中使用序号来导入函数:
#include <windows.h>
#include <stdio.h>
int main()
{
typedef int (* AddFunc)(int, int);
HMODULE hModule = LoadLibrary("dll.dll");
AddFunc add = (AddFunc)GetProcAddress(hModule, MAKEINTRESOURCE(1)); //注意这里序号的指定方式
printf("%d\n", add(1, 2));
return 0;
}