Usando Run-Time Ligação Dinâmica
Você pode usar a mesma DLL tanto na ligação dinâmica no tempo de carregamento quanto no tempo de execução. O exemplo a seguir usa a função LoadLibrary para obter um identificador para a DLL Myputs (consulte Creating a Simple Dynamic-Link Library). Se LoadLibrary for bem-sucedida, o programa utilizará o identificador retornado na função GetProcAddress para obter o endereço da função myPuts da DLL. Depois de chamar a função DLL, o programa chama a função FreeLibrary para descarregar a DLL.
Como o programa usa vinculação dinâmica em tempo de execução, não é necessário vincular o módulo a uma biblioteca de importação para a DLL.
Este exemplo ilustra uma diferença importante entre vinculação dinâmica em tempo de execução e em tempo de carga. Se a DLL não estiver disponível, o aplicativo que usa a vinculação dinâmica em tempo de carregamento deve simplesmente ser encerrado. O exemplo de vinculação dinâmica em tempo de execução, no entanto, pode responder ao erro.
// 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;
}
Tópicos relacionados