0

Is it not possible to access the data in the memory of a TidBytes buffer with typecasting? Say I have:

type
    TMyRecord = packed record
        Field1 : integer ;
        Field2 : packed array [0..1023] of byte ;
        end ;  

var
  Buffer    : TIdBytes ;
  MyRecord  : TMyRecord ;

begin
  IdTCPClient1.IOHandler.ReadBytes (Buffer, SizeOf (TMyRecord), false) ;

  with TMyRecord (Buffer) do            // compiler snags with "invalid typecast"
  ...

OK, so I can use:

BytesToRaw (Buffer, MyRecord, SizeOf (TMyRecord)) ;

but is there no way of accessing the data directly without the overhead of copying it?

TLama
  • 75,147
  • 17
  • 214
  • 392
rossmcm
  • 5,493
  • 10
  • 55
  • 118

1 Answers1

3

Is it not possible to access the data in the memory of a TidBytes buffer with typecasting?

TIdBytes is a dynamic array of bytes, so you have to use a type-cast if you want to interpret its raw bytes in any particular format.

is there no way of accessing the data directly without the overhead of copying it?

A dynamic array is implemented by the compiler/RTL as a pointer to a block allocated elsewhere in memory. So you can use a pointer type-cast to interpret the content of the block, eg:

type
  PMyRecord = ^TMyRecord;
  TMyRecord = packed record
    Field1 : integer ;
    Field2 : packed array [0..1023] of byte ;
  end ;  

var
  Buffer: TIdBytes ;
begin
  IdTCPClient1.IOHandler.ReadBytes (Buffer, SizeOf(TMyRecord), false) ;
  with PMyRecord(Buffer)^ do
    ...
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks Remy. I had tried all the combinations I could think of using `^`, `addr`, and `TMyRecord`, I didn't think to try defining a pointer type. BTW, should the first word of your answer be *Yes*, rather than *No*? – rossmcm Mar 26 '15 at 20:07
  • You asked if it were possible to access the data without typecasting, and that answer is *No*. But I have re-worded the answer. – Remy Lebeau Mar 26 '15 at 20:45