补充,以下是delphi官方网站上的提示:
As mentioned earlier, AnsiString types are always null-terminated, so they’re compatible with
null-terminated strings. This makes it easy to call Win32 API functions or other functions
requiring PChar-type strings. All that’s required is that you typecast the string as a PChar.
(Typecasting is explained in more detail in the section “Typecasting and Type Conversion.”)
The following code demonstrates how to call the Win32 GetWindowsDirectory() function,
which accepts a PChar and buffer length as parameters:
var
S: string;
begin
SetLength(S, 256)
// important! get space for string first
// call function, S now holds directory string
GetWindowsDirectory(PChar(S), 256);
end;
After using an AnsiString in which a function or procedure expects a PChar, you must manually
set the length of the string variable to its null-terminated length. The RealizeLength()
function, which also comes from the StrUtils unit, accomplishes that task:
procedure RealizeLength(var S: string);
begin
SetLength(S, StrLen(PChar(S)));
end;
Calling RealizeLength() completes the substitution of a long string for a PChar:
var
S: string;
begin
SetLength(S, 256)
// important! get space for string first
// call function, S now holds directory string
GetWindowsDirectory(PChar(S), 256);
RealizeLength(S)
// set S length to null length
end;