问题描述
每个线程是否有任何标准方法跨平台进行语言环境设置?我看到xlocale提供uselocale,但Windows不支持.有"_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);"在Windows中,之后setlocale将基于每个线程工作.我的问题是,是否有一个以平台独立的方式提供这些特定于语言环境的操作的库???还是其他方式?
Is there any standard way doing locale setting across platforms per thread? I see that xlocale provides uselocale, but it is not supported in Windows. There is "_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);" in windows, after which setlocale works on per thread basis. My question is, is there a library that provides these locale specific manipulations in a platform independent way??? Or some other way of doing it?
谢谢,Gokul.
推荐答案
我遇到了同样的问题,最终我为它编写了一些小的跨兼容性代码.我尝试尽可能遵循规范,但是它确实有一些限制.
I've had the same problem and I eventually wrote some small cross-compatibility code for it. I tried to follow the specification as close as possible, but it does have a few limitations.
在此代码中, newlocale 不允许您指定基础语言环境,您也无法混合类别遮罩.但是,对于不同区域之间的一些基本切换,就足够了.
In this code newlocale does not allow you to specify a base locale and you're also not able to mix the category masks. But for some basic switching between different locales this should be enough.
// Locale Cross-Compatibility
#ifdef _WIN32
#define locale_t _locale_t
#define freelocale _free_locale
#define LC_GLOBAL_LOCALE ((locale_t)-1)
#define LC_ALL_MASK LC_ALL
#define LC_COLLATE_MASK LC_COLLATE
#define LC_CTYPE_MASK LC_CTYPE
#define LC_MONETARY_MASK LC_MONETARY
#define LC_NUMERIC_MASK LC_NUMERIC
#define LC_TIME_MASK LC_TIME
// Base locale is ignored and mixing of masks is not supported
#define newlocale(mask, locale, base) _create_locale(mask, locale)
locale_t uselocale(locale_t new_locale)
{
// Retrieve the current per thread locale setting
bool bIsPerThread = (_configthreadlocale(0) == _ENABLE_PER_THREAD_LOCALE);
// Retrieve the current thread-specific locale
locale_t old_locale = bIsPerThread ? _get_current_locale() : LC_GLOBAL_LOCALE;
if(new_locale == LC_GLOBAL_LOCALE)
{
// Restore the global locale
_configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
}
else if(new_locale != NULL)
{
// Configure the thread to set the locale only for this thread
_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
// Set all locale categories
for(int i = LC_MIN; i <= LC_MAX; i++)
setlocale(i, new_locale->locinfo->lc_category[i].locale);
}
return old_locale;
}
#endif
将该代码放入您的项目中,您就可以在任何平台上切换每个线程的语言环境:
Put that code in your project and you'll be able to switch the locale per-thread on any platform like this:
#include <locale.h>
#ifdef __APPLE__
#include <xlocale.h>
#endif
// Apply a new locale to this thread
locale_t locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
locale_t old_locale = uselocale(locale);
// Print out some text
printf("Always use dot-decimal notation: %f", 1.5);
// Restore the global locale
uselocale(old_locale);
freelocale(locale);
这篇关于C ++中特定于线程的语言环境操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!