Re: Fwd: wide char string literals to Glib ustring
- From: Chris Vine <chris cvine freeserve co uk>
- To: Onur Tugcu <onur tugcu gmail com>
- Cc: gtkmm-list gnome org
- Subject: Re: Fwd: wide char string literals to Glib ustring
- Date: Sun, 09 Dec 2007 17:26:57 +0000
On Sun, 2007-12-09 at 11:13 -0500, Onur Tugcu wrote:
> Thank you,
>
> You're right. Most of the confusion was from my failed test on ucs4.
> I thought I wrote that code below and it threw an exception on linux.
> But apparently I was wrong, or missed something in the code.
>
> Now it is simply:
>
> #include <iostream>
> #include <ostream>
> #include <locale>
> #include <glibmm/ustring.h>
> #include <glibmm/convert.h>
> #include <glib/gmem.h>
>
> template <int= sizeof(wchar_t)>
> struct w2ustring_select;
>
> template <>
> struct w2ustring_select<2>
> {
> typedef gunichar2 const* gunistr_t;
> gchar* (*fun)(gunistr_t, glong, glong*, glong*, GError**);
> w2ustring_select(): fun(g_utf16_to_utf8){}
> };
>
> template <>
> struct w2ustring_select<4>
> {
> typedef gunichar const * gunistr_t;
> gchar* (*fun)(gunistr_t, glong, glong*, glong*, GError**);
> w2ustring_select(): fun(g_ucs4_to_utf8){}
> };
>
> Glib::ustring w2ustring(std::wstring const &w)
> {
> static w2ustring_select<> which;
> typedef w2ustring_select<>::gunistr_t whichstr_t;
> whichstr_t whatever= reinterpret_cast<whichstr_t>(w.c_str());
> gchar* utf8= which.fun(whatever, -1, 0, 0, 0);
> Glib::ustring u(utf8); g_free(utf8);
> return u;
> }
>
> int main()
> {
> std::locale::global(std::locale("")); // phew, I didn't know!
> std::wstring w(L"üö");
> Glib::ustring u(w2ustring(w));
> }
>
> Which works on the few target platforms including windows, so the
> issue is resolved.
> (sorry if that specialization is worse than an "if" or could be done better.)
> Now with my editors I can write unicode directly into string literals.
For printing to a terminal, you can also use printf()/snprintf() with
the %ls format specifier, which might be more efficient as it invokes
wcsrtombs() directly, and also avoids the need for templated conversions
depending on the size of wchar_t. Thus, the following will display wide
character string literals in a locale independent way:
printf("%ls\n", L"üö");
To use the output with GTK+ widgets, you would have to pass the string
handed off by snprintf() back through Glib::locale_to_utf8().
Chris
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]