動態連結程式庫兩種使用方法
一
1. Dll
.h檔案
#ifdef DLL1_API
#else
#define DLL1_API _declspec(dllimport)
#endif
DLL1_API int Add(int a,int b);
DLL1_API int Sub(int a,int b);
class DLL1_API Point
{
public:
void Output(int x,int y);
};
.cpp檔案
#define DLL1_API _declspec(dllimport)
#include "Dll1.h"
#include <windows.h>
#include <stdio.h>
int Add(int a,int b)
{
return a+b;
}
int Sub(int a,int b)
{
return a-b;
}
void Point::Output(int x,int y)
{
HWND hwnd;
hwnd=GetForegroundWindow();
HDC hdc=GetDC(hwnd);
char buf[20];
memset(buf,0,20);
sprintf(buf,"x=%d,y=%d",x,y);
TextOut(hdc,0,0,buf,strlen(buf));
ReleaseDC(hwnd,hdc);
}
調用Dll 把編譯產生的.dll和.lib檔案放在程式目錄下,把Dll的.h檔案也要拷貝到引用程式目錄下。Project->Setting->Link 設定 Object/library modules的lib檔案位置。如"Debug/Dll3.lib"。
添加引用檔案 #include "Dll1.h"
void CDllTestDlg::OnBtnAdd()
{
// TODO: Add your control notification handler code here
CString str;
str.Format("5+3=%d",Add(5,3));
MessageBox(str);
}
void CDllTestDlg::OnBtnSub()
{
// TODO: Add your control notification handler code here
CString str;
str.Format("5-3=%d",Sub(5,3));
MessageBox(str);
}
void CDllTestDlg::OnBtnOutput()
{
// TODO: Add your control notification handler code here
Point pt;
pt.Output(5,3);
}
二 .def方式 解決名字改編問題,不同的語言使用問題。
在程式目錄下建立個尾碼名為:def檔案,在Project->Add To Project\Files 添加到工程中。
dll
.def
LIBRARY Dll3
EXPORTS
Add
.cpp
int _stdcall Add(int a,int b)
{
return a+b;
}
調用
.h
_declspec(dllimport) int _stdcall Add(int a,int b);
.cpp
void CDll3TestDlg::OnBTNAdd()
{
CString str;
str.Format("5+3=%d",Add(5,3));
MessageBox(str);
}
以上調用的方式都是隱式連結方式載入方式實現對動態連結程式庫訪問
動態載入方式
void CDll3TestDlg::OnBTNAdd()
{
HINSTANCE hInst;//dll 控制代碼
hInst=LoadLibrary("Dll3.dll");//動態載入Dll
typedef int(_stdcall *lpAdd)(int,int);//定義函數指標類型
lpAdd AddFun=(lpAdd)GetProcAddress(hInst,"Add");
if(!AddFun)
{
MessageBox("擷取函數地址失敗!");
return;
}
CString str;
str.Format("5+3=%d",AddFun(5,3));
FreeLibrary(hInst);//不需要訪問Dll,釋放
MessageBox(str);
}
總結.def的方式能解決跨語言問題,個人比較推崇這種方法。歡迎留言,正在學習C++