Is there a clean way to declare a value compatible with TBytes at compile time?

If I wanted to declare a static byte compilation time array, I could do it like this:

var bytes :array[0..24] of Byte = (1, 2, 3, .... ); 

However, the type of this array is [0..24] bytes, not System.TArray<System.Byte> , which is better known as TBytes .

I need something like TBytes, but I don't want to add an initialization section to hold these byte values ​​in some painful way:

 var bytes2:TBytes; initialization SetLength(bytes2,24); bytes2[0] := 1; bytes2[1] := 2; .... 

Is there a way to do this instead:

 var bytes2:TBytes = (1,2,3, .... ); 

I also tried to find a way to quickly convert from TBytes ( System.TArray<System.Byte>) and array [0..24] Byte, for example:

  bytes2 := byte; 

Unfortunately, the closest I can get is brute force code:

  SetLength(bytes2,Length(bytes)); for n := 0 to Length(bytes) do begin bytes2[n] := bytes[n]; end; 

It seems to me that the two types are so closely related to each other that the compiler can improve the work a bit, allowing me to force or copy, from one type to another. Does anyone else think of the different types of "Array X" like that? Know any steep paths around him? If the compiler did some magic, it could make the Move (...) function work in this case, but Move actually gives you access violation and cannot be used with dynamic arrays or generic collections.

+4
source share
1 answer

What about:

 var bytes: TBytes; begin bytes := TBytes.Create(1,2,3, .... ); end; 

This says that I always think that it is a limitation that this syntax does not accept open arrays. So I have a bunch of functions that look like this:

 function Bytes(const A: array of Byte): TBytes; var i: Integer; begin SetLength(Result, Length(A)); for i := low(Result) to high(Result) do Result[i] := A[i]; end; ... var b1, b2: TBytes; b3: array of Byte; b4: array [0..42] of Byte; ... b1 := Bytes(b2); b1 := Bytes(b3); b1 := Bytes(b4); b1 := Bytes([1,2,3,4]); 

I believe that the various generic enhancements in XE mean that this could be done with generics and without duplicating routines like Bytes for every other scalar.

+4
source

Source: https://habr.com/ru/post/1342151/


All Articles