What if I have a dynamic array and want to pass it to a function as an open array argument?
procedure DoThis(const Args: array of const);
procedure DoThat(const Values: TArray<String>);
begin
DoThis(Values);
end;
What should I convert the dynamic array to in order to pass it as an open array? (The static array is transferred without problems.)
You can't specify an open array as the result of a function, so you can't solve the problem this way. I tried using var open array to convert a dynamic array, but var open array cannot set the length. The thing is we can not control the length of an open array, only use an open array constructor. Maybe there is a way to write data in memory directly? Or something else?
Let me emphasize that when DoThis
would be declared like
procedure DoThis(const Args: array of string);
calling DoThis(Values)
would work right out of the box. It is the const
in array of const
that is the problem here.
Unit System.Rtti.pas provides function TValueArrayToArrayOfConst
suitable to create an array of const
, but it requires an TArray<TValue>
to do so. So to convert an TArray<T>
into an array of const
a similar function could look like this:
type
TConvert = record
public
class function ConvertToArrayOfConst<T>(const Params: TArray<T>): TArray<TVarRec>; static;
end;
class function TConvert.ConvertToArrayOfConst<T>(const Params: TArray<T>): TArray<TVarRec>;
var
I: Integer;
begin
SetLength(Result, Length(Params));
for I := Low(Result) to High(Result) do
Result[I] := TValue.From<T>(Params[I]).AsVarRec;
end;