I need move the data stored in a array of bytes to a set of records located in a TList, but i’m getting this error
E2197 Constant object cannot be passed as var parameter
This code reproduce the issue.
uses
System.Generics.Collections,
System.SysUtils;
type
TData = record
Age : Byte;
Id : Integer;
end;
//this code is only to show the issue, for simplicity i'm filling only the first
//element of the TList but the real code needs fill N elements from a very big array.
var
List : TList<TData>;
P : array [0..1023] of byte;
begin
try
List:=TList<TData>.Create;
try
List.Count:=1;
//here i want to move the content of the P variable to the element 0
Move(P[0],List[0], SizeOf(TData));
finally
List.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
How i can copy the contents of a buffer to a TList Element
In XE2, the internal storage for
TList<T>is opaque and hidden. You cannot gain access to it by normal means. All access to elements of the list are copied – references to the underlying storage are not available. So you cannot blit to it usingMove. If you want a structure that you can blit to, you should consider a dynamic array,TArray<T>.You can always use the trick of implementing a class helper for
TList<TData>that would expose the private variableFItems. That’s pretty hacky but will do what you ask.I guess you might want to put some parameter checking in
TListTDataHelper.Blit, but I’ll leave that to you.If you were using XE3, you could access the private storage of
TList<T>by using theListproperty.If you don’t need to blit and can use a for loop then do it like this:
But I interpret your question that you wish to avoid this option.