Menggunakan Run-Time Pengaitan Dinamis
Anda dapat menggunakan DLL yang sama dalam penautan dinamis waktu muat dan waktu jalan. Contoh berikut menggunakan fungsi LoadLibrary untuk mendapatkan handle ke DLL Myputs (lihat Membuat Pustaka Dynamic-Link Sederhana). Jika LoadLibrary berhasil, program menggunakan handle yang dikembalikan dalam fungsiGetProcAddressuntuk mendapatkan alamat dari fungsi myPuts pada DLL. Setelah memanggil fungsi DLL, program memanggil fungsiFreeLibraryuntuk membongkar DLL.
Karena program menggunakan penautan dinamis run-time, tidak perlu menautkan modul dengan pustaka impor untuk DLL.
Contoh ini mengilustrasikan perbedaan penting antara penautan dinamis run-time dan load-time. Jika DLL tidak tersedia, aplikasi yang menggunakan penautan dinamis waktu muat hanya harus dihentikan. Namun, contoh penautan dinamis run-time dapat merespons kesalahan.
// 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;
}
Topik terkait