String Delphi

Title: StringlistToVariant / VariantToStringlist
Question: The OLE type variant allows you to transfer nearly everything via
DOM/DCOM what you need.
This demo shows how to convert a stringlist into a variant and vice
versa.
Answer:
unit uForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
hStrList: TStringList;
v: OleVariant;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure VariantToStream(const Data: OleVariant; Stream: TStream);
var
p: Pointer;
begin
p := VarArrayLock(Data);
try
Stream.Write(p^, VarArrayHighBound(Data,1) + 1); //assuming low bound = 0
finally
VarArrayUnlock(Data);
end;
end;
function StreamToVariant(Stream: TStream): OleVariant;
var
p: Pointer;
begin
Result := VarArrayCreate([0, Stream.Size - 1], varByte);
p := VarArrayLock(Result);
try
Stream.Position := 0; //start from beginning of stream
Stream.Read(p^, Stream.Size);
finally
VarArrayUnlock(Result);
end;
end;
function StringlistToVariant(aStrlist: TStrings): OleVariant;
var
hStream: TStream;
begin
hStream := TMemoryStream.Create;
try
aStrList.SaveToStream(hStream);
hStream.Seek(0,soFromBeginning);
Result := StreamToVariant(hStream);
finally
hStream.Free;
end;
end;
procedure VariantToStringlist(const Data: OleVariant; aStrlist: TStrings);
var
hStream: TStream;
begin
hStream := TMemoryStream.Create;
try
VariantToStream(Data,hStream);
hStream.Seek(0,soFromBeginning);
aStrList.LoadFromStream(hStream);
finally
hStream.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
hStrList:= TStringList.Create;
hStrList.Assign(Memo1.Lines);
v := StringlistToVariant(hStrList);
hStrList.Destroy;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
VariantToStringlist(v,Memo2.Lines);
end;
end.