Search code examples
delphiunicodelocalizationdelphi-7ansi

Widestring to string conversion in Delphi 7


my app is a non-unicode app written in Delphi 7.

I'd like to convert unicode strings to ANSI with this function :

function convertU(ws : widestring) : string;
begin
  result := string(ws);
end;

I use also this code to set the right codepage to convert.

initialization
  SetThreadLocale(GetSystemDefaultLCID);
  GetFormatSettings;

It works great in the VCL main thread but not in a TThread, where I get some questions marks '?' as result of function convertU.

Why not in a TThread ?


Solution

  • Calling SetThreadLocale() inside of an initialization block has no effect on TThread. If you want to set a thread's locale, you have to call SetThreadLocale() inside of the TThread.Execute() method.

    A better option is to not rely on SetThreadLocale() at all. Do your own conversion by calling WideCharToMultiByte() directly so you can specify the particular Ansi codepage to convert to.