How to convert PAnsiChar to WideString or string?

Little Helper picture Little Helper · Apr 24, 2011 · Viewed 49.4k times · Source

How do I convert a PAnsiChar variable to WideString or to string?

Answer

David Heffernan picture David Heffernan · Apr 24, 2011

You simply assign one variable to another and let the Delphi compiler do all the conversion for you:

var
  p: PAnsiChar;
  s: string;
  w: WideString;
....
s := p;
w := p;

If you want to convert in the other direction, and restricting the discussion to Delphi 7 for which Char, PChar, string are all ANSI data types you would use the following:

PAnsiChar(s);
PAnsiChar(AnsiString(w));

The casts are needed when going in this direction and in the case of the WideString the data must be explicitly converted from Unicode to ANSI before asking for a null-terminated C string pointer.