使用 Run-Time 動態連結
您可以在載入時間和執行時間動態連結中使用相同的 DLL。 下列範例會使用 LoadLibrary 函式來取得 Myputs DLL 的控制代碼(請參閱 建立簡單 Dynamic-Link 函式庫)。 如果 LoadLibrary 成功,程式會使用 GetProcAddress 函式中的傳回句柄來取得 DLL myPuts 函式的位址。 呼叫 DLL 函式之後,程式會呼叫 FreeLibrary 函式來卸除 DLL。
因為程式使用運行時間動態連結,所以不需要連結模組與 DLL 的匯入連結庫。
此範例說明運行時間與載入時間動態連結之間的重要差異。 如果 DLL 無法使用,則使用載入時間動態連結的應用程式必須直接終止。 不過,運行時間動態連結範例可以回應錯誤。
// A simple program that uses LoadLibrary and
// GetProcAddress to access myPuts from Myputs.dll.
#include <windows.h>
#include <stdio.h>
typedef int (__cdecl *MYPROC)(LPCWSTR);
int main( void )
{
HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
// Get a handle to the DLL module.
hinstLib = LoadLibrary(TEXT("MyPuts.dll"));
// If the handle is valid, try to get the function address.
if (hinstLib != NULL)
{
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts");
// If the function address is valid, call the function.
if (NULL != ProcAdd)
{
fRunTimeLinkSuccess = TRUE;
(ProcAdd) (L"Message sent to the DLL function\n");
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}
相關主題