Click here to Skip to main content
Click here to Skip to main content

Windows SetThreadLocale and CRT setlocale

By , 15 Feb 2005
 

Sample Image

Introduction

Some countries and languages standardize on number and date formats that don't translate smoothly between cultures. It is important for C++/Windows developers to have strategies and techniques to handle this challenge and other challenges presented by diverging sets of localization API functions. The CtrSynch sample app illustrates how to keep the Windows API locale in synch with the C-runtime (CRT) locale so that functions like LoadString are in step with conversion routines like _tprintf.

Background

Have you ever encountered a situation where you need to read a double/floating point value from text formatted in another locale? For example, the number 1023.54 displays in English-US as 1,023.54 and in German-Germany as 1.023,54. This problem comes up often when sharing text-based information generated in Europe (Germany, France, Spain) and consumed in the US. The reverse is also true.

Say, a German company exports a Tab Separated text (TSV) file from a spreadsheet on a workstation running in the German-Germany locale. The file is emailed to an American firm, where values like 1.023,54 import as a decimal number between 1 and 2 rather than 1023. This is a very common scenario.

The first step in properly transferring double values (or dates formatted by locale defaults) is to include a locale identifier in the data. This can be accomplished using a file header, an LCID field in each data row, embedded logic in the file name, and so on. In my simple example, I just wrote a method to pack an LCID onto the end of the string containing the number. Conversely, I wrote a routine to parse it back out before reading the number. The final issue is the actual conversion of the text to doubles. My first instinct was to run SetThreadLocale, run the _tcstod function on the text, then return to the previous thread locale.

It doesn't work! I spent a lot of time trying to figure this out, and I hope to save you the effort!

It turns out, the C-runtime routine _tcstod (strtod in ANSI, wcstod in UNICODE) gets its locale context from the C-runtime function setlocale. SetThreadLocale does not talk to setlocale. Therefore, calling SetThreadLocale without calling setlocale puts you in a situation where LoadString will load from the current thread locale, but _tprintf will format in the locale the application started under. So, should you just call setlocale at the same time you call SetThreadLocale?

Well, I wish it was that simple! Here is what must happen in your code to keep the thread locale in step with the CRT's locale:

SetThreadLocale(1033);
setlocale(LC_ALL, "English_USA.1252");

You probably see the problem -- the two functions consume very different input parameters. After struggling with this, I found the solution is actually quite simple. It just required digging in the Windows API a bit. setlocale has two parameters, and the second is a three token string. The first is a language, the second is a country or region, and the third is a code page identifier. It turns out, these three values are readily acquired through the Windows API GetLocaleInfo. Therefore, given an LCID value, one may call GetLocaleInfo to find its language name (in English), it's region (in English), and its code page. A snippet:

LPCTSTR CCrtLocaleSwitch::loadLocaleId(LCID lcid, _bstr_t& bstrRetBuf)
{
    TCHAR arcBuf[128];
    memset(arcBuf, 0, sizeof(arcBuf));

    //We should check the return code, but skipped for brevity...
    //Loading the English name fo the locale
    GetLocaleInfo( lcid, LOCALE_SENGLANGUAGE, arcBuf, 127);
    bstrRetBuf = arcBuf;
    memset(arcBuf, 0, sizeof(arcBuf));
    //Loading the English name for the country/region
    GetLocaleInfo( lcid, LOCALE_SENGCOUNTRY, arcBuf, 127);
    if( *arcBuf )
    {
        bstrRetBuf += TEXT("_");
        bstrRetBuf += arcBuf;
    }
    //Loading the code page
    memset(arcBuf, 0, sizeof(arcBuf));
    if( (GetLocaleInfo( lcid, LOCALE_IDEFAULTANSICODEPAGE, arcBuf, 127)
        || GetLocaleInfo( lcid, LOCALE_IDEFAULTCODEPAGE, arcBuf, 127))
        &&  *arcBuf )
    {
        bstrRetBuf += TEXT(".");
        bstrRetBuf += arcBuf;
    }
    return bstrRetBuf;
}

The function above creates the string that is acceptable for setlocale. This allows you to keep the C-runtime's locale in synch with the Windows API locale state.

One final note regarding the sample application -- the sample classes are designed to restore state when they go out of scope. Regardless of how you exit a function, whether it's a normal return or an exception event, the previous locale will be restored. For brevity, I did not always check return values when calling Windows API or CRT functions, so please bear with my laziness!

Using the code

The sample application was written in Visual C++ 7.1. The two main reusable classes, CTempLocale and CSmartBuf, should be compatible with other compilers. The simplest way to use these classes is to put them in a folder in your header file search path, then add the following to your stdafx.h file:

#include <comdef.h>
#include <TempLocale.h>

The application itself is rather useless, but it illustrates keeping the CRT in synch with the Windows thread locale. When you select a new culture on the left, the window caption changes to "Hello World" in the selected language. Since MFC's CString internally calls LoadString, this functionality gets its locale from the Windows SetThreadLocale function. At the time the caption changes, the number in the lower left is reformatted per the selected locale, and that formatting gets its locale from the last call to the CRT setlocale function. On the right, you can select a target culture to translate the displayed number into, and it is displayed in the lower right. This lower-right number illustrates one possible way to attach LCID info to text containing a decimal number.

Conclusion

The Windows API provides routines to load resources in the current thread's locale. The CRT provides routines to convert numbers to text and back again. The two sets of APIs don't share a locale status; therefore, C++ developers must build a way to keep them in synch. This article demonstrated a way to handle this task.

History

  • Version 1.0, 2005-02-13.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

About the Author

Chris Grimes
Software Developer (Senior)
United States United States
Member
Director of Software Engineering for a startup software/hardware solution provider based in Silicon Valley. Currently in search of a new position with another company.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: SetThreadLocale questionmemberGary Wheeler4 Mar '05 - 2:00 
Thanks for the answer, Chris; I think I understand what SetThreadLocale is supposed to do. Here's a little better explanation of what I'm seeing.
 
My application includes both English and Japanese resources. The app displays English resources properly if I don't use SetThreadLocale. When logged in with the UI language set to English, I can use SetThreadLocale to set the locale to Japanese at startup, and my app will use the Japanese resources. When I log in with the UI language set to Japanese, and I use SetThreadLocale to set the locale to English, I still get the Japanese resources. This is on Windows XP Pro, English, with the multilingual user pack installed (Japanese language).
 
I'm wondering if this is caused by the multilingual pack (which isn't the same thing as using a localized version of Windows).
 
This app is getting installed on PC's running Windows XP localized to Japanese. Our manufacturing people want to run tests with the app in English (since none of them speak Japanese Smile | :) ).
 
If you have any suggestions, I'd appreciate it.
 

Software Zen: delete this;
GeneralRe: SetThreadLocale questionmemberChris Grimes5 Mar '05 - 11:33 
Without running an interactive debug session and seeing the code, it's only possible to speculate.   I would suggest that you   write a message including the thread LCID to a log file or debug monitor right before your windows are created.   Do this from the thread creating the application windows.   The thread locale will likely be Japanese.   The question is why the thread starts up in Japanese.   Maybe SetThreadLocale fails, or maybe the SetThreadLocale call is nested in an if or case block such that it does not run.   Put messages on both sides of the call to verify that it runs and succeeds.
 
Further, could there be a piece of code that resets the thread locale?   A destructor of a some class could do this under the radar.
 
Maybe the window creation process itself resets the thread locale to the Windows UI locale, which could easily be detected from within your window procedure or a message handler.   This behavior could vary between MLP and localized Windows.
 
One other thing, what about the language bar?   I'm exposing my ignorance here, but I'm not sure what effect it has on a running application and how it interacts with regional settings.
 
Regards,
Chris
GeneralRe: SetThreadLocale questionmemberAtul Kumar Dwivedi12 Nov '05 - 2:37 
Please provide little more information so that I can help you little better. What resources you are using in your application. Does the resources are in japanese or in english, or both.
 

 
Atul Kumar Dwivedi
India
Generalsetlocale in a threadmemberBadJerry22 Feb '05 - 2:02 
Hi Chris,
 
Very interesting article and I wished I had read found something that clear years ago.It would have saved me months of weird (and failed) experiments. I have a question though... I have a program that deals with different locales at run-time and it is multithreading!
 
So here is my question: is there a setlocale function that would be spread specific? Is there a way to do this without having to synchronise all my threads whenever I want CString::Format(_T("%g"),... for instance in English or French?
 
Any help/idea/pointer welcome!
 
Best regards,
BadJerry
GeneralRe: setlocale in a threadmemberMartin Richter24 Feb '05 - 0:18 
AFAIK setlocale is thread local, so each thread can call the CRT setlocale function without changing the locale of another thread.
This is the case if the multithreading CRT is in use.
GeneralRe: setlocale in a threadsussLeft215 Mar '05 - 6:04 
You are wrong.
At least as I see from MSVC 7.1 CRT source code, setlocale change the locale for all threads.
GeneralRe: setlocale in a threadmemberJeffrey Walton7 Dec '07 - 6:09 
Hi Left2,
 
Left2 wrote:
You are wrong.

You might want to look at Configure Thread Locale[^].
 
Jeff
GeneralSetThreadLocale ...memberCP Visitor17 Feb '05 - 6:28 
... sounds like 'Set Thread Local Storage' but is obviously something entirely different Sigh | :sigh:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 16 Feb 2005
Article Copyright 2005 by Chris Grimes
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid