-1

I am using Delphi XE3, and with the following code:

function Test(): string;
var
  Buffer: array[0..5] of WideChar;
  BufferLen: Cardinal;
  TempStr: UnicodeString;
begin
  SetString(TempStr, PWideChar(@Buffer[0]), BufferLen / 2);
end;

I always get the following error:

[dcc32 Error] Translator.pas(148): E2008 Incompatible types

But I check Does SetString have two version for AnsiString and UnicodeString accordingly? and confirm there are two versions of SetString, why does not work for Unicode?

Ken White
  • 123,280
  • 14
  • 225
  • 444
alancc
  • 487
  • 2
  • 24
  • 68
  • 4
    SetString works perfectly for UnicodeString but it takes an integer for the third arg and you passed a floating point value. I also wonder what that divide by two is meant to do. Normally you'd pass a length in that argument. Why would you want to be passing half the length? – David Heffernan Aug 06 '23 at 06:50
  • 1
    My guess is that you are imagining that BufferLen contains the size, i.e. number of bytes. Well if that was so you'd use div 2 or div SizeOf(Char) or div SizeOf(Buffer[0]). But a variable named BufferLen should contain a length (element count) rather than a size (byte count). You get the length of an array using the Length function, which works with fixed length arrays also. – David Heffernan Aug 06 '23 at 07:01
  • 5
    If you are using XE3 why would you tag the question delphi-xe2. Details matter and this inattention to details will likely hinder your programming too. – David Heffernan Aug 06 '23 at 07:02
  • @DavidHeffernan, you are correct, the problem comes from the BufferLen / 2. I pay too much attention to the UnicodeString. After changing BufferLen / 2 to BufferLen div 2, the issue disappears. The reason I use delphi-xe2 instead, because there is no tag delphi-xe3 available. – alancc Aug 06 '23 at 10:38
  • No 'delphi-xe3' tag available? As you can see from my edit, there certainly is one, and has been since XE3 was released. Just note that all 'delphi-...' tags are not shown when you type 'delphi', you may need to type the '-xe' also or even '-xe3'. – Tom Brunberg Aug 06 '23 at 16:59
  • BufferLen div 2 may compile but it sounds like it's still a bug – David Heffernan Aug 06 '23 at 17:24
  • @DavidHeffernan, what bug? – alancc Aug 07 '23 at 03:57
  • Dividing length by 2 seems like a bug – David Heffernan Aug 07 '23 at 11:22
  • You should learn the basic Delphi operators. You've confused floating point division `/` with integer division `div`. The result of `BufferLen / 2` with `BufferLen = 10` would be the floating point value `5.0`, and the result with `BufferLen = 15` would be `7.5`. Neither of those values is appropriate to provide as the third arg to `SetString`, which is an integer. – Ken White Aug 08 '23 at 03:08

0 Answers0