Delen via


Dynamische koppeling Run-Time gebruiken

U kunt hetzelfde DLL-bestand gebruiken in dynamische koppelingen voor zowel laadtijd als runtime. In het volgende voorbeeld wordt de functie LoadLibrary gebruikt om een ingang naar het DLL-bestand myputs te krijgen (zie Een eenvoudige Dynamic-Link bibliotheek maken). Als LoadLibrary slaagt, gebruikt het programma de geretourneerde ingang in de functie GetProcAddress om het adres van de functie myPuts van het DLL-bestand op te halen. Nadat de DLL-functie is aangeroepen, roept het programma de FreeLibrary- functie aan om het DLL-bestand te verwijderen.

Omdat het programma gebruikmaakt van dynamische runtimekoppelingen, is het niet nodig om de module te koppelen aan een importbibliotheek voor het DLL-bestand.

In dit voorbeeld ziet u een belangrijk verschil tussen dynamische koppeling tussen runtime en laadtijd. Als het DLL-bestand niet beschikbaar is, moet de toepassing die dynamische koppeling laadtijd gebruikt, gewoon beƫindigen. Het voorbeeld van dynamische koppeling in runtime kan echter reageren op de fout.

// 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;

}

Run-Time dynamische koppeling