问题
Is it possible to mimic the loadlibrary
function? I want to load a library from a BLOB field without first writing it to a temporary file, and I need a solution which is not dependent on specific version of delphi compiler or windows, and does not trigger antivirus software.
回答1:
dzlib contains a ready made object for reading a dll from a resource into memory and using it without ever saving it to disc:
This is the main file ...
http://sourceforge.net/p/dzlib/code/147/tree/dzlib/trunk/src/u_dzResourceDllLoader.pas
.. but it needs other files from the same repository.
回答2:
Yes you can, and you need not loadlibrary
to execute a code from memory - you need to allocate a memory using VirtualAlloc function with PAGE_EXECUTE flag set
Update: here is a quick and dirty demo of the code executed from memory for 32-bit Delphi - I only tested that it works:
type
TIncMe = procedure(var I: Integer);
var
IncMeProc: TIncMe;
procedure IncMe(var I: Integer);
begin
Inc(I);
end;
procedure CopyIncMe;
var
Size: LongWord;
Tmp: Pointer;
begin
Size:= LongWord(@CopyIncMe) - LongWord(@IncMe);
Tmp:= VirtualAlloc(nil, Size, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
Move(Pointer(@IncMe)^, Tmp^, Size);
IncMeProc:= Tmp;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
J: Integer;
begin
J:= 0;
CopyIncMe;
while J < 10 do begin
IncMeProc(J);
ShowMessage(IntToStr(J));
end;
VirtualFree(@IncMeProc, 0, MEM_RELEASE);
end;
回答3:
There's an article on delphi.about.com, that shows how to load a dll from a resource.
It first loads the resource into memory, and then loads the dll from the resource using Memory Module
Instead of a resource, you can use a database or whatever source you want to load the dll from. Once it is in a memory stream, you can use the following code to load and execute the dll functions, which looks very much like 'normal' code to invoke a dll:
var
btMM: PBTMemoryModule;
begin
btMM := BTMemoryLoadLibary(mp_DllData, m_DllDataSize);
try
if btMM = nil then Abort;
@m_TestCallstd := BTMemoryGetProcAddress(btMM, 'TestCallstd');
if @m_TestCallstd = nil then Abort;
m_TestCallstd('This is a Dll Memory call!');
except
Showmessage('An error occoured while loading the dll: ' + BTMemoryGetLastError);
end;
if Assigned(btMM) then BTMemoryFreeLibrary(btMM);
end;
来源:https://stackoverflow.com/questions/12171769/how-can-i-execute-code-directly-from-memory-in-delphi