Tuesday, 15 April 2014

string - Is there any compiler magic in PChar / PWideChar / PAnsiChar casts? -



string - Is there any compiler magic in PChar / PWideChar / PAnsiChar casts? -

i read compiler kind of magic when casting pchar.

the main purpose of pchar phone call foreign code in libraries expect 0 terminated array of characters (c style "string").

pchar type alias pwidechar on unicode delphi , alias pansichar on non-unicode delphi.

delphi strings (string = ansistring / unicodestring, i'm not talking widestring here, allow lone shortstring ...) on other hand have hidden length instead of termination char. reference counted , utilize re-create on write.

are delphi strings automatically allocated , kept 1 char longer implicit #0 char in order create casting pchar (pansichar / pwidechar) easier or compiler check , adjust string when encounters conversion pchar?

the process follows:

if string s has length greater zero, pchar(s) returns pointer first element of string content. because string managed have hidden null-terminator nil more needs done. if string s has length zero, pchar(s) returns pointer block of memory containing null-terminator.

as implementation detail, null-terminator returned pchar(nil) global constant allocated in read-only section of compiled module.

are delphi strings automatically allocated , kept 1 char longer implicit #0 char in order create casting pchar (pansichar / pwidechar) easier?

yes.

the magic, if can phone call that, that:

using pchar() on empty strings returns pointer null-terminator. delphi maintains hidden null-terminator @ end of string.

string delphi pointers casting

No comments:

Post a Comment