Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Passing variable pointer as string to another function

I don't know if it is even possible, but what I need is to access (use and free) a TStream variable by it pointer, passed thought a string parameter to another function.

Here is a "not working" example of what I am trying to do:

procedure TForm1.Button1Click(Sender: TObject);
var
  Stm: TMemoryStream;
begin
  Stm := TMemoryStream.Create;
  try
    Memo.Lines.SaveToStream(Stm);
    Stm.Position := 0;
    Memo.Clear;
    Edit.Text := IntToStr(Integer(@Stm));
  except
    Stm.Free;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  PStm: ^TMemoryStream;
begin
  PStm := Pointer(StrToInt(Edit.Text));
  try
    Memo.Lines.LoadFromStream(PStm^);  // <--- Access Violation
  finally
    PStm^.Free;
  end;
end;

Thanks for any help to solve this!

like image 439
Guybrush Avatar asked Nov 29 '25 23:11

Guybrush


1 Answers

TStream is a reference type. Your Stm variable holds a pointer to the stream object instance. You want to pass this pointer value, not the address of the local variable. Here's the fixed code:

procedure TForm1.Button1Click(Sender: TObject);
var
  Stm: TMemoryStream;
begin
  Stm := TMemoryStream.Create;
  try
    Memo.Lines.SaveToStream(Stm);
    Stm.Position := 0;
    Memo.Clear;
    Edit.Text := IntToStr(Integer(Stm));
  except
    Stm.Free;
    raise;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Stm: TMemoryStream;
begin
  Stm := Pointer(StrToInt(Edit.Text));
  try
    Memo.Lines.LoadFromStream(Stm);
  finally
    Stm.Free;
  end;
end;
like image 165
Ondrej Kelle Avatar answered Dec 01 '25 13:12

Ondrej Kelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!