Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Memory copy with Record to another Record

I am having problem with the logic. I have no idea how to copy record to another record in Delphi.

TypeA = record
  value1 : word;
  value2 : word;
  value3 : word;
  end;

TypeB = record
  b1 : byte;
  b2 : byte;    
  end;

I have my two records TypeA and TypeB. For example, I found out that data in TypeA record is belong to TypeB records. Note: TypeA has longer Data Length.

Question: How do i copy TypeA memory and place it in TypeB record?

CopyMemory(@TypeA, @TypeB, Length(TypeB))

When i tried CopyMemory and got an error (Incompaible types).

PS: I don't want to copy or assign it like below.

TypeB.b1 := TypeA.value1 && $FF;

TypeA and TypeB are just example records. Most of thecases, record TypeA and TypeB may contain multple records and it will be harder to allocate form TypeA and assign to TypeB record.

Thanks in advance

----Addition question:

Is there a way to copy Delphi record to Byte array and how? If there is,

  • TypeA record to Byte Array
  • Byte Array to Type B

Will this logic work?

like image 782
sMah Avatar asked Nov 28 '22 09:11

sMah


2 Answers

CopyMemory(@a, @b, SizeOf(TypeB))

if a is of type TypeA and b is of type TypeB.

like image 117
Andreas Rejbrand Avatar answered Dec 05 '22 05:12

Andreas Rejbrand


Variant records:

TypeA = packed record
  value1 : word;
  value2 : word;
  value3 : word;
  end;

TypeB = packed record
  b1 : byte;
  b2 : byte;
  end;

TypeAB = packed record
  case boolean of
    false:(a:TypeA);
    true:(b:TypeB);
end;
..
..
var someRec:TypeAB;
    anotherRec:TypeAB;
..
..
  anotherRec.b:=someRec.b
like image 37
Martin James Avatar answered Dec 05 '22 06:12

Martin James