Load DLL from block of memory - how to use?
I found a block with functions that allow loading DLLs directly from memory, but I don't know how to use it.
This is the unit: http://www.delphibasics.info/home/delphibasicssnippets/udllfrommem-loadadllfrommemory
I know that the function:
function memLoadLibrary(FileBase : Pointer) : Pointer;
But I don't know how I can use it, what is the FileBase I need to define, etc.
Can anyone help me?
+3
source to share
2 answers
You just need to put the DLL in memory and pass memLoadLibrary a pointer to the location of the DLL in memory.
For example, from a resource:
hRes := LoadResource(HInstance, 'MYRESNAME'); if hres=0 then RaiseLastOSError; BaseAddress := LockResource(hRes); if BaseAddress=nil then RaiseLastOSError; lib := memLoadLibrary(BaseAddress); .....
+4
source to share
Let's say you have both a procedure and a function in your DLL that you want to load from memory in order to use them:
** GLOBAL ** (both, exe -> dll)
type
TTest1Proc = record
Proc: procedure; StdCall;
hLib: THandle;
end;
TTest2Func = record
Func: function: Boolean; StdCall;
hLib: THandle;
end;
** DLL **
procedure Test1; StdCall;
begin
ShowMessage('Test proc');
end;
function Test2: Boolean; StdCall;
begin
Result := True;
end;
exports
Test1.
Test2;
This is how you can load the dll and use both methods (procedures and functions) in the .EXE project:
procedure Test1;
var
Test1Proc: TTest1Proc;
begin
with Test1Proc do
begin
hLib := LoadLibrary(PChar('DLL_PATH.dll'));
if hLib <> 0 then
begin
@Proc := GetProcAddress(hLib, 'Test1');
if Assigned(Proc) then
try
Proc; //will execute dll procedure Test1
finally
FreeLibrary(hLib);
end
else
ShowMessage('Procedure not found on DLL');
end
else
ShowMessage('DLL not found.');
end;
end;
And as a function:
function Test2: Boolean;
var
Test2Func: TTest2Func;
begin
Result := False;
with Test2Func do
begin
hLib := LoadLibrary(PChar('DLL_PATH.dll'));
if hLib <> 0 then
begin
@Func := GetProcAddress(hLib, 'Test2');
if Assigned(Func) then
try
Result := Func; //will execute the function Test2
finally
FreeLibrary(hLib);
end
else
ShowMessage('Function not found on DLL.');
end
else
ShowMessage('DLL not found.');
end;
end;
+1
source to share