I often read that the compiler does some kind of magic when casting to PChar.
The main purpose of PChar is to call foreign code in libraries that expect a zero terminated array of characters (C style “string”).
PChar is a type that is an alias to PWideChar on Unicode Delphi and an alias to PAnsiChar on non-unicode Delphi.
Delphi strings (string = AnsiString / UnicodeString, I’m not talking about WideString here, let alone ShortString …) on the other hand have a hidden length instead of a termination char. They are also reference counted and use copy on write.
Are Delphi strings automatically allocated and kept to be one char longer with an implicit #0 char in order to make casting to a PChar (PAnsiChar / PWideChar) easier or does the compiler check and adjust the string when it encounters a conversion to PChar?
The process is as follows:
shas length greater than zero, thenPChar(s)returns a pointer to the first element of the string content. Because thestringis managed to have a hidden null-terminator nothing more needs to be done.shas length zero, thenPChar(s)returns a pointer to a block of memory containing a null-terminator.As an implementation detail, the null-terminator that is returned from
PChar(nil)is a global constant allocated in the read-only section of the compiled module.Yes.
The magic, if you can call it that, is that:
PChar()on empty strings returns a pointer to a null-terminator.