title: Convert array to array of const in Delphi
body: <p>I am looking for a simple and ideally general (or using generics) way to convert an <code>array</code> to an <code>array of const</code> (=<code>array of TVarRec</code>). My specific case is that I have an <code>array of Variant</code> and want to pass it to the <code>Format()</code> function.</p>
  
  <p>This is what I've found so far, but it looks hackish to me:</p>
  
  <pre><code>function MyFormat(const Fmt: string; const Args: TArray&lt;Variant&gt;): string;
  var
    A: array of TVarRec;
    I: Integer;
  begin
    SetLength(A, Length(Args));
    for I:= Low(Args) to High(Args) do begin
      A[I].VType:= vtVariant;
      A[I].VVariant:= @Args[I];
    end;
    Result:= Format(Fmt, A);
  end;
  </code></pre>
  
  <p>It seems to work. Is it safe?</p>
  
  <p>Could it be done shorter, better, faster, or can I use something ready instead? :)</p>
  
  <hr>
  
  <p>Just some additional thoughts and fun facts:</p>
  
  <p><code>System.Rtti.TValue</code> recently became my friend. However, it seems it is missing a feature here. I am able to read my array using <code>TValue.From()</code>, but it seems there is no way to get it out as <code>array of TVarRec</code>. There is a wonderful <code>TValueArrayToArrayOfConst</code>, but it doesn't really help, because I had to construct an <code>array of TValue</code> first, which is different from an array stored in a single <code>TValue</code>... :(</p>
  
  <p>At least TValue is able to output a single element as TVarRec, so I thought I could create a generic converter for all types of arrays. But...</p>
  
  <p>Would you think this works?</p>
  
  <pre><code>for I:= Low(Args) to High(Args) do A[I]:= TValue.From(Args[I]).AsVarRec;
  </code></pre>
  
  <p>It compiles, but <code>TValue</code>'s memory is released after use, and since <code>TVarRec.VVariant</code> is a pointer, it then points to some old location which is overridden on next cycle.</p>