简体   繁体   中英

Delphi 2007, Indy 10. Why can't I typecast a TidBytes buffer?

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM