c++ - LoadString 是否为其写入的字符串分配内存?

标签 c++ resources stringreader resourcestring

我是 C++ 新手,需要一些帮助。 我创建了一个包含字符串的纯资源 dll,我需要在不同的项目中使用此 dll 来读取存储的字符串。

我编写了以下函数来读取字符串:

LPTSTR GetResourceStr(HMODULE resContainer,int resourceID)
{
    //The stings that are stored in the dll are:
    //
    //ID            |Value|Caption
    //__________________________________________
    //IDS_STRING101 |101  |stringggg
    //IDS_STRING102 |102  |string 102
    //IDS_STRING103 |103  |string 103

    LPTSTR strBuffer = NULL;//is a (non-const) TCHAR string
    if(0!=resContainer){
      int copied=LoadString(resContainer,resourceID ,(LPTSTR)&strBuffer,0); 
    }
    return strBuffer;
}

int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE resContainer=LoadLibraryEx(L"ResourceDll.dll",NULL, LOAD_LIBRARY_AS_DATAFILE);

    LPTSTR msg = GetResourceStr(resContainer,101);
    std::wcout<<msg<<std::endl;
    //Expected output: stringggg
    //The output that i get: stringgggstring 102 string 103
    int i = 0;
    std::cin>>i;
    return 0;
}

我应该在代码中更改什么才能获得预期输出 - stringggg? 为什么会发生这种情况? LoadString 是否为从资源中读取的字符串分配了内存,或者我只是获得了指向字符串已存储在内存中的位置的指针? 感谢您的帮助!!

最佳答案

LoadString documentation说:

nBufferMax [in]

Type: int

The size of the buffer, in characters. The string is truncated and null-terminated if it is longer than the number of characters specified. If this parameter is 0, then lpBuffer receives a read-only pointer to the resource itself.

因此,要直接回答您的问题,您只需获得一个指向存储资源的内存的指针。

但是字符串资源不是以 null 结尾的(有关详细信息,请参阅 here ),因此这就是您获得该输出的原因。 LoadString 的返回值告诉您单个字符串资源的长度。如果需要字符串以 null 结尾,则必须将字符串复制到单独的缓冲区,如下所示:

WCHAR* pszString;
int iLength = ::LoadString(
    resContainer,
    resourceID,
    reinterpret_cast<LPWSTR>(&pszString),
    0
    );

WCHAR* pszString2 = new WCHAR[iLength + 1];
::StringCchCopyN(pszString2, iLength + 1, pszString, iLength);

或者,您可以使用指向缓冲区的指针(而不是指向指针的指针)作为第三个参数,并将缓冲区的长度作为第四个参数来调用 LoadString,这会将字符串资源复制到缓冲区并将其空终止。缺点是如果传递的长度不够大,字符串会被截断,并且无法预先查询资源的长度。

关于c++ - LoadString 是否为其写入的字符串分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41257672/

相关文章:

java - 可重用的 Java StringReader

c++ - Eclipse c++ 方法无法解析

c++ - 将一种类型的 STL 对象存储到另一种类型的有效方法

c++ - qobject 基础的多重继承

python - 驻留集大小 (RSS) 限制无效

java - 我应该关闭 StringReader 吗?

c++ - 在 tr1 中为模板类定义散列

java - Spring Boot 2.1.9.RELEASE - 读取资源文件

javascript - 设置不同资源的优先级

java - StringReader 从 String.Split 输出中给出错误