Converting buffers

If you have specialized needs, or just don't want to use wxString, you can also use the conversion methods of the conversion objects directly. This can even be useful if you need to do conversion in a non-Unicode build of wxWidgets; converting a string from UTF-8 to the current encoding should be possible by doing this:

wxString str(wxConvUTF8.cMB2WC(input_data), *wxConvCurrent);

Here, cMB2WC of the UTF8 object returns a wxWCharBuffer containing a Unicode string. The wxString constructor then converts it back to an 8-bit character set using the passed conversion object, *wxConvCurrent. (In a Unicode build of wxWidgets, the constructor ignores the passed conversion object and retains the Unicode data.)

This could also be done by first making a wxString of the original data:

wxString input_str(input_data);
wxString str(input_str.wc_str(wxConvUTF8), *wxConvCurrent);

To print a wxChar buffer to a non-Unicode stdout:

printf("Data: %s\n", (const char*) wxConvCurrent->cWX2MB(unicode_data));

If you need to do more complex processing on the converted data, you may want to store the temporary buffer in a local variable:

const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(unicode_data);
const char *tmp_str = (const char*) tmp_buf;
printf("Data: %s\n", tmp_str);

If a conversion had taken place in cWX2MB (i.e. in a Unicode build), the buffer will be deallocated as soon as tmp_buf goes out of scope. (The macro wxWX2MBbuf reflects the correct return value of cWX2MB (either char* or wxCharBuffer), except for the const.)

ymasuda 平成17年11月19日