Delphi XE3 indy compatibility issue between tbytes and tidbytes

北战南征 提交于 2019-12-06 10:49:50

The two Unpack methods receive parameters of type TBytes. So you need to pass variables that are of that type. You are passing variables of type array of Byte which is not assignment compatible with TBytes.

Fix the problem by declaring your variables to be TBytes instead of array of Byte.

Type compatibility in Delphi is a bit of a mess. Personally, I always use the generic dynamic array which has more relaxes compatibility rules. So I would choose to use TArray<Byte> rather than TBytes if I was in control of all the code involved.

Another option for you is to use open arrays which are the most flexible parameters. For instance.

class function Unpack(const Bytes: array of Byte; Count: Integer): TOSCPacket;

That function can be passed variables of type TBytes, TIdBytes, array of Byte, TArray<Byte>, open array constructors, static byte arrays, etc.

Note that you should also declare array parameters as const to avoid the overhead of making copies of them.

Update 1

It becomes clear that AData is in fact an open array and is not a dynamic array. In which case you should make your function receive open arrays.

I think that your code is executing inside a method of type TUDPReadEvent:

type
  TUDPReadEvent = procedure(AThread: TIdUDPListenerThread; AData: array of Byte; 
    ABinding: TIdSocketHandle) of object;

In which case TIdBytes is not relevant, there is nothing of that type here. And AData is not a dynamic array, it is an open array parameter. So you will need to declare your functions to use open arrays also.

As an aside, it looks to me as though the Indy people messed up in the declaration of TUDPReadEvent. The AData parameter really should be passed as const. See Remy's comment: it was Emba that messed this up.

You should read the documentation of open array parameters to make sure that you fully understand the difference between an open array parameter and a dynamic array.

Update 2

If you cannot modify either of these interfaces, then you must simply place an adapter between them. For instance:

function CopyBytes(const Bytes: array of Byte): TBytes;
var
  Count: Integer;
begin
  Count := Length(Bytes);
  SetLength(Result, Count);
  if Count > 0 then
    Move(Bytes[0], Result[0], Length(Bytes));
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!