6

In my Delphi VCL Form application I've a procedure which has a TBuff parameter (defined before as array of byte). Inside this procedure, I have to convert the parameter to a string.

procedure Form1.Convert(Collect: TBuff);
var 
   str: String;
begin
   str := SysUtils.StringOf(Collect);
end;

After the compile, I was warned about the presence of this compiler error:

Incompatible types :'System.TArray<System.TByte>' and 'TBuff'

0

1 Answer 1

13

The problem that you encounter is that you have defined your own byte array type like this:

type
  TBuff = array of Byte;

This private type of yours is not assignment compatible with other byte array types. Most RTL functions that use byte arrays use the RTL type TBytes which is declared as TArray<Byte>.

The first thing for you to do is to remove TBuff from your program and instead use TBytes. If you continue to use TBuff you will find that all your byte array code lives in its own ghetto, unable to interact with library functionality that uses TBytes. So, escape the ghetto, and remove your TBuff type from existence.

Now, in order to convert a byte array to a string, you need to provide encoding information to do this. You have selected StringOf which should be considered a legacy function these days. It is better to be more explicit in your conversion and use TEncoding.

For instance, if the byte array is UTF-8 you write:

str := TEncoding.UTF8.GetString(ByteArray);

If the byte array is encoded in the local ANSI encoding you write:

str := TEncoding.ANSI.GetString(ByteArray);

In your case the use of StringOf indicates that the byte array is ANSI encoded so this latter example is what you need.

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

2 Comments

Just a note that Delphi XE2 added the .ANSI property to TEncoding that you can use instead of .Default (which now returns UTF8 if you are on Mac OSX.) In cases where I know the byte array is ANSI I've switch to using the .ANSI property to be more explicit (and also in case they decide to change the default meaning.)
@MarkF they won't change the meaning of Default, but the code is better written explicitly as you suggest. I changed it. Thanks.

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.