1

我正在制作一个 win32 程序,它是一个关卡编辑工具,与我为 2D 瓷砖系统创建的库一起使用。

当用户从菜单中选择它时,我想创建显示地图属性的对话框。这意味着从 int 到 wchar_t 数组的转换。我创建了一个我希望能做到这一点的函数。但是目前它只返回一个空白字符串,返回变量被初始化为。此转换对于使用地图属性对话框调用的 SetDlgItemText() 函数是必需的。

这是我目前拥有的功能:

LPWSTR IntToLPWSTR(int value)
{
    std::ostringstream  convert;
    std::string         out;

    convert << value;
    out = convert.str();

    const char*             in;
    in = out.c_str();

    LPWSTR ret = L"";
    MultiByteToWideChar(CP_ACP, MB_COMPOSITE, in, strlen(in), ret, wcslen(ret));

    return ret;
}

从这里调用它:

    case WM_INITDIALOG:
        if (mapToEdit)
        {
            SetDlgItemText(hDlg, IDC_TILE_WIDTH_LBL, IntToLPWSTR(mapToEdit->TileWidth()));
            SetDlgItemText(hDlg, IDC_TILE_HEIGHT_LBL, L"");
            SetDlgItemText(hDlg, IDC_MAP_WIDTH_LBL, L"");
            SetDlgItemText(hDlg, IDC_MAP_HEIGHT_LBL, L"");
        }
        else
        {
            EndDialog(hDlg, LOWORD(wParam));
            MessageBox(hWnd, L"You must create a map first", L"Error", 1);
        }

Map to edit is simply a pointer to my own map class that contains the properies I want to display. The bottom three calls to SetDlgItemText() pass L"" as their string, the intention is that they will also use the function when it works.

4

2 回答 2

4

std::to_wstring is simpler, but to point out the problem in your code, you never created a buffer. LPWSTR ret = L""; makes ret a pointer to an array held in static memory. This array cannot be modified.

Here is one way to fix the code by using std::wstring as the buffer:

std::wstring IntToWstring(int value)
{
    std::ostringstream  convert;
    std::string         out;

    convert << value;
    out = convert.str();
    std::wstring ret;
    // Find proper length
    int length = MultiByteToWideChar(CP_ACP, 0, out.c_str(), out.length(), nullptr, 0);
    ret.resize(length);
    // Probably should also check for errors (got rid of MB_COMPOSITE flag)
    MultiByteToWideChar(CP_ACP, 0, out.c_str(), out.length(), &ret[0], length);

    return ret;
}

If you don't want to use std::wstring you could dynamically allocate a buffer LPWSTR ret = new LPWSTR[length];.

EDIT

Also, keep in mind that you could simplify the code to the following:

std::wstring IntToWstring(int value)
{
    std::wostringstream  convert;

    convert << value;
    convert.str();
}
于 2013-05-17T21:32:48.483 回答
0

You don't need to go to a lot of effort to convert an int into a const wchar_t *. Since C++11, you can take a two-step approach to a std::wstring and a const wchar_t * from there:

SetDlgItemText(hDlg, IDC_TILE_WIDTH_LBL, std::to_wstring(mapToEdit->TileWidth()).c_str());

Sure you could put that into a function to make it one step, but keep in mind that you cannot let the std::wstring be destroyed by the time you use the pointer.

于 2013-05-17T21:30:39.007 回答