wBB
wBB

Reputation: 851

Copy the contents of array or memory block to another specific type, using Delphi

I need to copy the contents of an array to a variable of another type, as in the example below, but I can not find a solution. Note: I need this routine to work on Android with Delphi 10.

Does anyone know how to do this?

type TMyType = packed record
  Var_1: Byte;
  Var_2: Byte;
  Var_N: Byte;
end;

Var aa: TMyType;
    vArr: TByte;
begin

  vArr := [1, 2, 3];

  // Copy vArr content to "aa" like this
  aa :=  @vArr;

  // aa.Var_1 = 1;
  // aa.Var_2 = 2;
  // aa.Var_N = 3;

Upvotes: -1

Views: 1019

Answers (1)

wBB
wBB

Reputation: 851

Vitória's solution was the one I used:

Move(vArr[0], aa, SizeOf(aa));

The corrected code looks like this:

type TMyType = record
  Var_1: Byte;
  Var_2: Byte;
  Var_N: Byte;
end;

Var aa: TMyType;
    vArr: array of Byte;
begin
   aa.Var_1 := 0;
   aa.Var_2 := 0;
   aa.Var_N := 0;

   vArr := [3, 4, 5];

   // Where "vArr[0]" is the pointer to the first memory location to be copied.
   // SizeOf must to be used for records/data structures and Length for arrays.
   Move(vArr[0], aa, SizeOf(aa));

// Result:
//   aa.Var_1 = 3
//   aa.Var_2 = 4
//   aa.Var_N = 5

Upvotes: -1

Related Questions