Bagikan melalui


Menggunakan Run-Time Dynamic Linking

Anda dapat menggunakan DLL yang sama dalam penautan dinamis waktu muat dan run-time. Contoh berikut menggunakan fungsi LoadLibrary untuk mendapatkan handel ke DLL Myputs (lihat Membuat Pustaka Dynamic-Link Sederhana). Jika LoadLibrary berhasil, program menggunakan handel yang dikembalikan dalam fungsi GetProcAddress untuk mendapatkan alamat fungsi myPuts DLL. Setelah memanggil fungsi DLL, program memanggil fungsi FreeLibrary untuk membongkar DLL.

Karena program menggunakan penautan dinamis run-time, tidak perlu menautkan modul dengan pustaka impor untuk DLL.

Contoh ini menggambarkan 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;

}

Penautan Dinamis Run-Time