Search code examples
arraysdelphiunicodemigrating

Changing from Array of AnsiChar to Array of WChar


I am XE5 user. I have a client/server app written in D7. I have upgraded to XE5. Because D7 was not unicode i have used following type:

TRap = array[0..254] of AnsiChar;

and i am sending this data to server over tcpip. Server has the same defination. Now i need to upgrade to unicode but size must be same. Because i am using the following modal:

PMovieData = ^TMovieData;
TMovieData = packed record
   rRap: TRap;
   rKey: string[7];
   iID: integer;
end;

i have tried to change TRap to this:

TRap2 = array[0..127] of WChar;

However sizes are not equal. TRap is 255 but TRap2 is 256. I can not change the size as it should work with ex version. Do you have any recommendations?


Solution

  • Well, since wide characters are 2 bytes wide, an array of wide characters has even size. And 255 is not even. So you cannot overlay an array of wide characters over the original array.

    I suppose you could have an array of 127 wide characters and a padding byte:

    TMovieData = packed record
      rRap: array [0..126] of WideChar;
      _reserved: Byte;
      rKey: string[7];
      iID: integer;
    end;
    

    I cannot imagine this would help much since an old component would interpret the wide character data as 8 bit data. Which would give unexpected results. Basically the text would be garbled.

    You might consider some other options:

    1. Continue with an array of 8 bit characters but encode as UTF-8. This would be compatible over the ASCII range. But any text in the 128-255 range would be garbled. Of course at the moment your existing solution can only work if both client and server use the same 8 bit character set.
    2. Switch all components to use a new record format. In fact if you did this you could abandon your rigid record format and serialize the record using JSON. Encode that as UTF-8 and transmit those bytes. This would also allow you to fix the problem with your current implementation that it doesn't respect network byte order.