c++, Win32 LoadString 包装器 [英] c++, Win32 LoadString wrapper

查看:46
本文介绍了c++, Win32 LoadString 包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想听听您对 LoadString Win32 函数的这个包装器的看法.

i would like to have your opinion about this wrapper for LoadString Win32 function.

int LoadWString( HINSTANCE hInstance_In, UINT uID_In, std::wstring &str_Out ){
    return LoadStringW( hInstance_In, uID_In, (LPWSTR)str_Out.c_str(), (int)str_Out.max_size());
}

因为它似乎按预期工作,问题更多是关于使用字符串 max_size 属性作为缓冲区大小,这是否有一些负面缺点?

as it seems to work as expected, question is more about using strings max_size property as buffer size, does this have some negative drawbacks?

推荐答案

c_str() 返回一个不可修改的指针.它不能被写入.抛弃常量并写入受控序列会导致未定义行为.

相反,只需查询指向资源部分的指针以及字符串长度,并在此数据上构造一个新的 std::wstring 对象:

Instead, simply query for a pointer into the resource section, together with the string length, and construct a new std::wstring object on this data:

std::wstring LoadStringW( unsigned int id )
{
    const wchar_t* p = nullptr;
    int len = ::LoadStringW( nullptr, id, reinterpret_cast<LPWSTR>( &p ), 0 );
    if ( len > 0 )
    {
        return std::wstring{ p, static_cast<size_t>( len ) };
    }
    // Return empty string; optionally replace with throwing an exception.
    return std::wstring{};
}

有几点值得注意:

  • 实现使用LoadString,传递<nBufferMax 的代码>0.这样做会返回一个指向资源部分的指针;不执行额外的内存分配:

nBufferMax:
如果此参数为 0,则 lpBuffer 会收到一个指向资源本身的只读指针.

nBufferMax:
If this parameter is 0, then lpBuffer receives a read-only pointer to the resource itself.

  • 字符串资源是计数字符串,可以包含嵌入的 NUL 字符.这要求使用 std::string 构造函数长度参数.return std::wstring(p); 可能会截断返回的字符串.
  • 由于字符串资源的布局,通常无法判断任何给定的字符串资源ID 为空或不存在.此答案中的实现也是如此,如果字符串资源为空或不存在,则返回一个空字符串.
    • String resources are counted strings, and can contain embedded NUL characters. This mandates the use of a std::string constructor taking an explicit length argument. return std::wstring(p); would potentially truncate the returned string.
    • Due to the layout of string resources, it is not generally possible to tell, if the string resource for any given ID is empty, or doesn't exist. The implementation in this answer follows suit, and returns an empty string if a string resource is empty, or does not exist.
    • 这篇关于c++, Win32 LoadString 包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆