UNICODE_STRING to wchar_t* null terminated

UNICODE_STRING to wchar_t* null terminated

本文关键字:null terminated wchar STRING to UNICODE      更新时间:2023-10-16

我想使用UNICODE_STRING中的缓冲区,但似乎我不能通过复制引用直接使用它,因为有时我可以看到字符串中间有空字节,Length大于我在调试器中看到的。所以如果我这样做

UNICODE_STRING testStr;
//after being used by some function it has data like this 'bad丣more_stuff'
wchar_t * wStr = testStr.Buffer;

我最终会得到wStr = "bad丣";有没有办法将其转换为以空结尾的有效wchar_t*

wchar_t*只是一个指针。 除非您告诉调试器(或将wchar_t*传递给的任何函数)实际指向的wchar_t字符数,否则它必须在某个地方停止,因此它会在遇到的第一个 null 字符处停止。

UNICODE_STRING::Buffer 不保证以 null 结尾,但它可以包含嵌入的 null。 你必须使用UNICODE_STRING::Length字段来知道Buffer中有多少个WCHAR元素,包括嵌入的空值,但不计算尾随的空终止符(如果存在)。 如果需要 null 终止符,请将Buffer数据复制到您自己的缓冲区并追加终止符。

最简单的方法是使用 std::wstring ,例如:

#include <string>
UNICODE_STRING testStr;
// fill testStr as needed...
std::wstring wStrBuf(testStr.Buffer, testStr.Length / sizeof(WCHAR));
const wchar_t *wStr = wStrBuf.c_str();

嵌入的 null 仍然存在,但c_str()将为您追加尾随的 null 终止符。 调试器仍将仅显示第一个 null 之前的数据,除非您告诉调试器数据中WCHAR元素的实际数量。

或者,如果您知道Buffer数据包含多个由 null 分隔的子字符串,则可以选择将Buffer数据拆分为字符串数组,例如:

#include <string>
#include <vector>
UNICODE_STRING testStr;
// fill testStr as needed...
std::vector<std::wstring> wStrArr;
std::wstring wStr(testStr.Buffer, testStr.Length / sizeof(WCHAR));
std::wstring::size_type startidx = 0;
do
{
    std::wstring::size_type idx = wStr.find(L'', startidx);
    if (idx == std::wstring::npos)
    {
        if (startidx < wStr.size())
        {
            if (startidx > 0)
                wStrArr.push_back(wStr.substr(startidx));
            else
                wStrArr.push_back(wStr);
        }
        break;
    }
    wStrArr.push_back(wStr.substr(startidx, idx-startidx));
    startidx = idx + 1;
}
while (true);
// use wStrArr as needed...

或:

#include <vector>
#include <algorithm>
UNICODE_STRING testStr;
// fill testStr as needed...
std::vector<std::wstring> wStrArr;
WCHAR *pStart = testStr.Buffer;
WCHAR *pEnd = pStart + (testStr.Length / sizeof(WCHAR));
do
{
    WCHAR *pFound = std::find(pStart, pEnd, L'');
    if (pFound == pEnd)
    {
        if (pStart < pEnd)
            wStrArr.push_back(std::wstring(pStart, pEnd-pStart));
        break;
    }
    wStrArr.push_back(std::wstring(pStart, pFound-pStart));
    pStart = pFound + 1;
}
while (true);
// use wStrArr as needed...

UNICODE_STRING是一个结构,它存储字符数据及其长度。因此,它允许嵌入NUL字符,就像std::wstring一样,例如。

C 样式字符串(例如 另一方面,wchar_t* ) 不存储显式字符串长度。按照惯例,它由 NUL 字符终止。它的长度是隐含的。由此推论,它不能包含嵌入的 NUL 字符。

这意味着您无法在不丢失长度信息的情况下从UNICODE_STRING转换为wchar_t*。您必须将长度与wchar_t*指针一起显式存储,或者建立解释规则,以允许重新计算长度(例如,通过将字符序列解释为以双 null 结尾的字符串)1)。


附加信息:
    没有字符串的
  • 双 null 结尾字符串的格式是什么?
  • 为什么使用以双 null 结尾的字符串而不是指向字符串的指针数组?


1)调试器会将wchar_t*解释为以零结尾的字符串。如果要查看整个序列,则需要使用格式说明符显式提供数组大小。