D2 string conversion

John C johnch_atms at hotmail.com
Sat May 9 09:09:08 PDT 2009


Sam Hu Wrote:

> Hello,
> 
> In D2 I tried to write a simple function which wrapps WIN32 API MessageBoxW,with which I can handle wide characters like Chinese .Below is my try:
> 
> import std.string;
> import std.conv;
> import std.c.windows.windows;
> 
> extern(Windows)int MessageBoxW(HWND,LPCSTR,LPCSTR,int);
> int showMessage(wchar[] msg,wchar[ ] caption=cast(wchar[])"Application",int style=MB_OK|MB_ICONINFORMATION)
> {
> return MessageBoxW(null,to!(const(char)[])(msg),to!(const(char)[])(caption),style);//try one
> return MessageBoxW(null,toStringz(to!(const(char[])(msg)),toStringz(to!(const(char)[])(caption)),style);//try two
> }
> 
> But both *try one* and *try two* the above are wrong.Anyone can figure me out what's the problem and what's the right way to do would be appreciated.
> 
> Sam

The problem is that you're calling the UTF-16 versions of the function with UTF-8 strings.

  extern(Windows) int MessageBoxW(HWND, in wchar*, in wchar*, int);

  int showMessage(wstring msg, wstring caption = "Application", int style = MB_OK | MB_ICONINFORMATION) {
    auto pszMsg = (msg ~ "\000").ptr;
    auto pszCaption = (caption ~ "\000").ptr;
    return MessageBoxW(HWND.init, pszMsg, pszCaption, style);
  }


More information about the Digitalmars-d-learn mailing list