Name

WideString Type

Syntax

type WideString;

Description

WideString is similar to AnsiString, but instead of storing a string of AnsiChar characters, it stores a Unicode string of WideChar (16-bit) characters. WideString keeps track of its length and automatically appends a #0 character to the end of the string so you can easily cast it to PWideChar.

Internally, Delphi stores a WideString as a pointer to a record, except that the pointer actually points to the Data member, and the Length is stored in the four bytes preceding the WideString pointer.

type
  // This is the logical structure of an WideString, but the
  // declaration below is descriptive and cannot be compiled.
  TWideString = record
    Length: LongWord;
    Data: array[1..Length+1] of WideChar;
  end;

Tips and Tricks

  • Like AnsiString, Delphi automatically manages the memory for WideString variables. Unlike AnsiString, WideString does not have a reference count, so every assignment of a WideString value results in a complete copy of the string. Thus, using WideString is less efficient than using AnsiString.

  • Delphi automatically converts between AnsiString and WideString, from PWideChar to WideString, and from a zero-based array of WideChar to WideString.

  • You can cast a WideString to PWideChar, which is often required for calling Windows API functions, but you must take the same care you take when casting an AnsiString to PChar. Delphi automatically frees the string when the string is no longer needed, but this also invalidates the PChar ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.