本文包括以下內容:
1. 如何編譯生成dll和lib文件
2. 如何在外部程序調用dll(動態鏈接)並訪問其函數
3. 如何在外部程序調用lib(靜態鏈接)並訪問其函數
一、如何編譯生成dll和lib文件
1. 新建Win32控制檯程序,勾選dll
2. 新建mydll.h文件,寫入代碼:
#ifndef _CLASS_H_
#define _CLASS_H_
//declaration
extern "C" __declspec(dllexport) int add(int a ,int b);
#endif
3. mydll.cpp文件,寫入代碼:
#include "stdafx.h"
#include "ClassDLL.h"
//implement
__declspec(dllexport) int add(int a ,int b)
{
return a+b;
}
二、外部調用dll
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
/*dynamic call*/
typedef int(*lpAddFun)(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
/* dynamic call */
HINSTANCE hDll;
lpAddFun addFun;
hDll = LoadLibrary(L"E:/ClassDLL.dll");
if (hDll != NULL)
{
addFun = (lpAddFun)GetProcAddress(hDll, "add");
if (addFun != NULL)
{
int result = addFun(2, 3);
cout<<result;
}
FreeLibrary(hDll);
}
return 0;
}
三、外部調用lib
#include "stdafx.h"
#include "DoorFSM.h"
#include <Windows.h>
#include <iostream>
using namespace std;
/*static call*/
#pragma comment(lib,"D:/ClassDLL.lib")
extern "C" __declspec(dllimport) int add(int x,int y);
int _tmain(int argc, _TCHAR* argv[])
{
/* static call */
int result = add(2,3);
cout<<result<<endl;
return 0;
}