How to convert a null terminated string to string?
You can assign a null-terminated PChar
directly to a String
:
function GetFileName(DiskName: TFileNameIO): string;
begin
Result := PChar(@DiskName);
end;
Just make sure the TDiskName
always contains a null terminator. If it can ever be completely full of characters without a null, you will have to do this instead:
function GetFileName(DiskName: TFileNameIO): string;
var
Len, I: Integer;
begin
Len := 0;
For I := Low(DiskName) to High(DiskName) do
begin
if DiskName[I] = #0 then Break;
Inc(Len);
end;
SetString(Result, PChar(@DiskName), Len);
end;
Your function is not necessary because you can simply assign a character array to a string variable.
type
TCharArray = array [1..512] of Char;
....
var
arr: TCharArray;
str: string;
....
arr := ...;
str := arr;
This results in str
being assigned the contents of arr
. The compiler implements this with a call to System._UStrFromWArray
which first of all looks for a null-terminator. If it finds one, that determines the length of str
. Otherwise, the entire contents of the array are copied, and Length(str)=Length(arr)
.
As a broader point, I would recommend that you change to using zero-based character arrays. From the documentation:
Zero-based character arrays are compatible with PChar and PWideChar. When you use a character array in place of a pointer value, the compiler converts the array to a pointer constant whose value corresponds to the address of the first element of the array.
This makes it easier for you to interop with functions that expect PChar
arguments.
As an aside, passing TFileNameIO
by value is inefficient because it involves a memory copy. Pass such types by reference. For instance as a const
parameter.