只能用 LoadLibrary( ) 來把 DLL 載入。
同時不要用的時候還可以用FreeLibrary( ) Free 掉。
但是要call DLL 中的 funciton 就比較麻煩了。
要用GetProcAddress ( ) 取出 DLL export 的 funciton address。
然後 cast 成 對應的 funciton ,才能使用。
為了..宣告 function pointer,cast funciton pointer,, 所以還是為每一個 export funciton typedef 一個 型別好了!!
所以好麻煩喔!
example 可以用 MSDN 的:
DLL 部份:Creatint a simple dynamic link library
#include <windows.h>
#define EOF (-1)
#ifdef __cplusplus // If used by C++ code,
extern "C" { // we need to export the C interface
#endif
__declspec(dllexport) int __cdecl myPuts(LPWSTR lpszMsg)
{
DWORD cchWritten;
HANDLE hConout;
BOOL fRet;
// Get a handle to the console output device.
hConout = CreateFileW(L"CONOUT$",
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (INVALID_HANDLE_VALUE == hConout)
return EOF;
// Write a null-terminated string to the console output device.
while (*lpszMsg != L'\0')
{
fRet = WriteConsole(hConout, lpszMsg, 1, &cchWritten, NULL);
if( (FALSE == fRet) || (1 != cchWritten) )
return EOF;
lpszMsg++;
}
return 1;
}
#ifdef __cplusplus
}
#endif
Call AP 要參考:
Using Run-Time dynamic Linking:
其實為了用那幾次的typedef 很麻煩,到不如反過來:
#include <windows.h>
#include <stdio.h&t;
typedef int (__cdecl *MYPROC)(LPWSTR);
VOID 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");
}
int (__cdecl *myPuts)(LPWSTR);
然後
*(FARPROC*)&myPuts = GetProcAddress(hinstLib, "myPuts");
沒有留言:
張貼留言