With Delphi 7 I need to create a TStream
variable and use/free it in another part of the code. Unfortunately it cannot be passed as "normal" parameter.
I created a simple application for testing what I need, using some examples I found on Google and some help from SOF (I am not used to pointers).
Here is what I got so far (it uses an Edit, a Memo e 3 Buttons):
function IsObject(Address: Pointer): Boolean; assembler;
asm
MOV EAX, [Address]
CMP EAX, EAX.vmtSelfPtr
JNZ @False
MOV Result, True
JMP @Exit
@False:
MOV Result, False
@Exit:
end;
procedure TForm1.btnSetMem1Click(Sender: TObject);
var
Stm: TStream;
begin
Stm := TMemoryStream.Create;
edtMemID1.Text := IntToStr(Integer(Stm));
end;
procedure TForm1.btnSaveMem1Click(Sender: TObject);
var
Stm: TStream;
begin
Stm := Pointer(StrToInt(edtMemID1.Text));
if IsObject(Stm) then
try
memStm1.Lines.SaveToStream(Stm);
btnSaveMem1.Enabled := False;
btnLoadMem1.Enabled := True;
memStm1.Clear;
except
FreeAndNil(Stm);
end;
end;
procedure TForm1.btnLoadMem1Click(Sender: TObject);
var
Stm: TStream;
begin
Stm := Pointer(StrToInt(edtMemID1.Text));
if IsObject(Stm) then
try
Stm.Position := 0;
memStm1.Lines.LoadFromStream(Stm);
except
FreeAndNil(Stm);
end;
end;
procedure TForm1.btnFreeMem1Click(Sender: TObject);
var
Stm: TStream;
begin
Stm := Pointer(StrToInt(edtMemID1.Text));
if IsObject(Stm) then FreeAndNil(Stm);
btnSaveMem1.Enabled := False;
btnLoadMem1.Enabled := False;
edtMemID1.Clear;
end;
procedure TForm1.edtMemID1Change(Sender: TObject);
begin
btnSaveMem1.Enabled := (Trim(edtMemID1.Text) <> '');
btnFreeMem1.Enabled := (Trim(edtMemID1.Text) <> '');
end;
The ASM function I found here and seems to be working. I also tested with FastMM and there is no memory leak (if btnFreeMem is used).
Please review this code and maybe give some tips to make it better or avoid problems (memory leaks).