tags:

views:

185

answers:

4

I wrote a function,which seperates two or more packets received in one physical packet.However,the compiler doesn't appreciate my effort. The size of every packet is in the first two bytes of the header of the packet,which is 6 bytes.so one real packet = it's first two bytes + 6.That's how I find if there is more than one packet.

procedure SeparatePackets(packet:pointer;size:word; out Result:Array of pointer; out number:byte);
var position:byte; //position
begin
  position:= 0;
  number:= 0;
  SetLength(Result,0); //<< ERROR

  while(PWord(Cardinal(packet) + position)^ + 6 <> size) do  //while the first two bytes + 6(packet header)
  begin
    SetLength(Result,Length(Result) + 1); //inc the length << ERROR
    Result[number] := Cardinal(packet) + position;
    position := Result[number] + PWord(Cardinal(packet) + position)^ + 6;
    inc(number);
  end;
end;

I marked the compile-time errors with '<< ERROR'. The error is one - 'Incompatible types'.

I never know the number of packets I may receive in one physical packet so I wanted to increase the length of the array if the number increases.

How do I solve my errors?

+5  A: 

How about creating a new type? I think it should work.

type
  TPntArray = array of Pointer;
bassfriend
+5  A: 

Declare a new type:

type
  TPointerDynArray = array of Pointer;

procedure SeparatePackets(Packet: Pointer; Size: Word; out Result: TPointerDynArray; out Number: Byte);
begin
  Result := nil; // unnecessary: dynamic out parameters are initialized to zero by compiler
  ...
end;
TOndrej
A: 

bassfriend and TOndrej have already shown you the solution. For background information read this - especially the part titled "Confusion".

Ulrich Gerhardt
+2  A: 

When you say array of X in a parameter declaration, what you have is an open array, not a dynamic array. Do as Bassfriend suggests and declare a named type for your array, and then use that type in your parameter declaration.

type
  TPointerArray = array of Pointer;

procedure SeparatePackets(packet: Pointer;
                          size: Word;
                          out Result: TPointerArray;
                          out number: Byte);

There's not much point in the number parameter. Dynamic arrays already know their own lengths, so the array by itself is sufficient. You don't need a separate value for the length, at least not as an output parameter. Furthermore, Byte isn't a very good type to use for holding the length of an array. The moment the array has more than 255 elements, you're in trouble. And finally, since the only thing this function does is construct an array, it seems to make more sense to turn it into a function:

function SeparatePackets(packet: Pointer; size: Word): TPointerArray;
Rob Kennedy