How to set string (or AnsiString) constant in the TVarRec?

user532231 picture user532231 · May 19, 2011 · Viewed 9.3k times · Source

I want to pass the formatting arguments Args into the Format function. I found some examples of that, but I can't find out how to assign string constant in the TVarRec member. The following code fails on compilation with E2089 Invalid typecast.

procedure TForm1.Button1Click(Sender: TObject);
var Arguments: array of TVarRec;
begin
  SetLength(Arguments, 2);

  Arguments[0].VInteger := 111;
  Arguments[1].VAnsiString :=  PAnsiString('Text'); // I want to set this member

  ShowMessage(Format('Decimal: %d, String: %s', Arguments));
end;

Can anyone suggest me how to set the string (or AnsiString) constant to the TVarRec member ? I'm using Delphi 2009.

Thanks a lot

Answer

Ondrej Kelle picture Ondrej Kelle · May 19, 2011

This seems to work in XE:

var
  Args: array[0..1] of TVarRec;
  S: AnsiString;
  U: UnicodeString;
begin
  S := 'Hello';
  U := 'world';
  Args[0].VType := vtAnsiString;
  Args[0].VAnsiString := Pointer(S);
  Args[1].VType := vtUnicodeString;
  Args[1].VUnicodeString := Pointer(U);

  Writeln(Format('%s, %s!', Args));
end;