简体   繁体   English

C ++,Win32 LoadString包装器

[英]c++, Win32 LoadString wrapper

i would like to have your opinion about this wrapper for LoadString Win32 function. 我想对LoadString Win32函数的此包装程序有您的意见。

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());
}

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? 正如预期的那样,问题更多是关于使用字符串max_size属性作为缓冲区大小,这是否有一些负面的缺点?

c_str() returns a non-modifiable pointer. c_str()返回一个不可修改的指针。 It must not be written to. 不得写入。 Casting away const-ness and writing to the controlled sequence results in undefined behavior . 抛弃常数并写入受控序列会导致不确定的行为

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对象:

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();
}

There are a few points worth noting: 有几点值得注意:

  • The implementation uses LoadString , passing 0 for nBufferMax . 该实现使用LoadString ,为nBufferMax传递0 Doing so returns a pointer into the resource section; 这样做会将指针返回到资源部分; no additional memory allocation is performed: 不执行其他内存分配:

    nBufferMax : nBufferMax
    If this parameter is 0, then lpBuffer receives a read-only pointer to the resource itself. 如果此参数为0,则lpBuffer接收指向资源本身的只读指针。

  • String resources are counted strings, and can contain embedded NUL characters. 字符串资源是计数字符串,并且可以包含嵌入的NUL字符。 This mandates the use of a std::string constructor taking an explicit length argument. 这要求使用带有显式length参数的std :: string构造函数。 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. 由于字符串资源布局,通常无法确定任何给定ID的字符串资源是否为空或不存在。 The implementation in this answer follows suit, and returns an empty string if a string resource is empty, or does not exist. 此答案中的实现也是如此,如果字符串资源为空或不存在,则返回一个空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM