gpt4 book ai didi

C++,Win32 LoadString 包装器

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:18 26 4
gpt4 key购买 nike

我想听听您对 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());
}

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

最佳答案

c_str()返回一个不可修改的指针。不得写入。放弃 const-ness 并写入受控序列会导致未定义的行为

相反,只需查询指向资源部分的指针以及字符串长度,并在此数据上构造一个新的 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{};
}

有几点值得注意:

  • 实现使用 LoadString ,为 nBufferMax 传递 0。这样做会返回一个指向资源部分的指针;没有执行额外的内存分配:

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

  • 字符串资源是计数字符串,可以包含嵌入的NUL 字符。这要求使用 std::string constructor采用显式长度参数。 return std::wstring(p); 可能会截断返回的字符串。
  • 由于 layout of string resources ,通常无法判断任何给定 ID 的字符串资源是否为空或不存在。此答案中的实现也是如此,如果字符串资源为空或不存在,则返回空字符串。

关于C++,Win32 LoadString 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com