How to assign byte [] records

In C ++, this is done as follows:

tPacket * packet = (tPacket *)data; //data is byte[] array; tPacket is a structure

In C #:

tPacket t = new tPacket();
GCHandle pin = GCHandle.Alloc(data, GCHandleType.Pinned);
t = (tPacket)Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(tPacket));
pin.free();

The data is a byte array used as a receive buffer after receiving a packet over TCP. This code puts the data in an instance of tPacket (structure), so I can access the structure later.

How is this done in Delphi?

+5
source share
3 answers

You can also use the absolute keyword to force both structures to use the same memory address:

var
  Data: array[1..SizeOf(TMyStruct)] of byte;
  s : TMyStruct absolute Data;

Any data written to S is also available as data without having to cast or pointer.

+4
source

Delphi , ++. , , Delphi .

type
  PPacket = ^TPacket;
var
  packet: PPacket;

packet := PPacket(@data[0]);
  • , @data[0], , , . , data , :

    packet := PPacket(data); // for dynamic array only
    

    data , -cast . data, :

    packet := PPacket(@data); // for static array only
    

    , . . ( , , ), , , data - , .


#-, TPacket, :

var
  packet: TPacket;

// Source param comes first. Params are passed by
// reference automatically.
Move(data[0], packet, SizeOf(packet));

, data TPacket. TPacket , string, Variant, IUnknown . - Move , .

+3

, , . , 2 , , :

:

type
  // Declare a pointer type for your struct.
  PMyStruct = TMyStruct^;

...

var
  ptr: PMyStruct;
begin
  ptr := PMyStruct(Cardinal(@Data));
  // use ptr...
end;

:

var
  Data: array of Byte;
  s: TMyStruct;
begin
  // fill Data...
  if SizeOf(s) <> Length(Data) then
    raise Exception.Create('Input size is not the same size as destination structure.');
  CopyMemory(@s, @Data, Length(Data));
  // use s...
end;
+2
source

All Articles