1

I have a c# project which I am trying to convert into Delphi.

I have a function addcoord

public static byte[] addCoord(Coordinate C, int ID)
{
    //Create an empty array of length 10
    byte[] ret = new byte[10];

    ret[0] = Convert.ToByte(newClass.Add);
    ret[1] = Convert.ToByte(ID);
    ret[2] = BitConverter.GetBytes(C.X)[0];
    //High-Byte of uInt16 X
    ret[3] = BitConverter.GetBytes(C.X)[1];
    //Low-Byte of uInt16 Y
    ret[4] = BitConverter.GetBytes(C.Y)[0];
    //High-Byte of uInt16 Y
    ret[5] = BitConverter.GetBytes(C.Y)[1];
    ret[6] = C.Red;
    ret[7] = C.Green;
    ret[8] = C.Blue;
    ret[9] = C.Master;

    return ret;
}

is there any equivalent to this in Delphi?

1 Answer 1

1

The Delphi equivalent of byte[] in C# is array of byte. You could either use it with a fixed size:

var
  buffer = array[0..9] of byte;

or with dynamic size

type
  TByteArray = array of byte;

function AddCoord(const C: TCoordinate; ID: integer): TByteArray;
begin
  SetLength(Result, 10); 

  Result[0] := C.Red; 
  Result[1] := C.Green; 
end;

For some basic types there are also predefined array types which should be preferred to use. For example TBytes.

Generics have been introduced in Delphi 2009. If you are using at least this version you should prefer to use TArray<T>. For example TArray<integer> or TArray<TMyType>.

Sign up to request clarification or add additional context in comments.

8 Comments

Delphi has built-in type TBytes for dynamic array of bytes, no need to introduce a user type TByteArray = array of byte;
Thanks. I just wanted to show how to create an array type on your own. But yes, you are right.
TBytes or TArray<Byte> will make it easier to interact with code from other libraries.
No, your example is very bad. Open arrays are very useful. They can accept static arrays and dynamic arrays. They are much more flexible. You do need to stop making inefficient copies though. Use const. And you can implement the open array version like this: function Foo(const Arr: array of Integer): Integer; begin Result := Length(Arr); end;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.