2

我需要将 UNICODE_STRING 结构转换为简单的 NULL TERMINATED STRING。

typedef 
struct _UNICODE_STRING 
{
    USHORT  Length;  
    USHORT  MaximumLength;  
    PWSTR   Buffer;
} 
UNICODE_STRING, *PUNICODE_STRING;

我在 MSDN 上找不到关于它的干净解决方案。有人去过吗?我没有使用 .net,所以我需要一个原生 API 解决方案。

非常感谢!

4

5 回答 5

4

您应该使用 WideCharToMultiByte。作为对输出缓冲区大小的估计,您可以使用 Length 字段 - 但请考虑真正的多字节字符串的情况,在这种情况下它将失败并显示 ERROR_INSUFFICIENT_BUFFER,并且您需要从更大的缓冲区重新开始。或者,您总是首先使用 0 的输出缓冲区大小调用它,因此它会告诉您缓冲区的必要大小。

于 2008-11-03T14:03:10.833 回答
2

在为 unicode 编译并转换为 ansi 时,这似乎对我有用
(从http://support.microsoft.com/kb/138813修改):

HRESULT UnicodeToAnsi(LPCOLESTR pszW, LPSTR* ppszA){
    ULONG cbAnsi, cCharacters;
    DWORD dwError;
    // If input is null then just return the same.    
    if (pszW == NULL)    
    {
        *ppszA = NULL;
        return NOERROR;
    }
    cCharacters = wcslen(pszW)+1;
    cbAnsi = cCharacters*2;

    *ppszA = (LPSTR) CoTaskMemAlloc(cbAnsi);
    if (NULL == *ppszA)
        return E_OUTOFMEMORY;

    if (0 == WideCharToMultiByte(CP_ACP, 0, pszW, cCharacters, *ppszA, cbAnsi, NULL, NULL)) 
    {
        dwError = GetLastError();
        CoTaskMemFree(*ppszA);
        *ppszA = NULL;
        return HRESULT_FROM_WIN32(dwError);
    }
    return NOERROR;
}


用法:

LPSTR pszstrA;
UnicodeToAnsi(my_unicode_string.Buffer, &pszstrA);
cout << "My ansi string: (" << pszstrA << ")\r\n";
于 2012-07-03T22:33:07.273 回答
1

转换为 ANSI 且不需要 UNICODE_STRING 中必须作为参数传递给 WideCharToMultiByte 的 unicode 字符数的替代代码。(请注意,UNICODE_STRING.Length 是字节数,而不是 unicode 字符,如果缓冲区不是以零结尾的,则 wcslen 不起作用)。

UNICODE_STRING tmp;
// ...
STRING dest; // or ANSI_STRING in kernel mode

LONG (WINAPI *RtlUnicodeStringToAnsiString)(PVOID, PVOID, BOOL);
*(FARPROC *)&RtlUnicodeStringToAnsiString = 
    GetProcAddress(LoadLibraryA("NTDLL.DLL"), "RtlUnicodeStringToAnsiString");
if(!RtlUnicodeStringToAnsiString)
{
    return;
}

ULONG unicodeBufferSize = tmp.Length;
dest.Buffer = (PCHAR)malloc(unicodeBufferSize+1); // that must be enough...
dest.Length = 0;
dest.MaximumLength = unicodeBufferSize+1;

RtlUnicodeStringToAnsiString(&dest, &tmp, FALSE);
dest.Buffer[dest.Length] = 0; // now we get it in dest.Buffer
于 2012-11-16T02:01:19.877 回答
0

由于您没有说是否需要 ANSI 或 UNICODE 以空字符结尾的字符串,我将假设 UNICODE:

#include <string>

UNICODE_STRING us;
// fill us as needed...

std::wstring ws(us.Buffer, us.Length);
// use ws.c_str() where needed...
于 2012-07-04T00:53:36.937 回答
0
WCHAR* UnicodeStringToNulTerminated(UNICODE_STRING* str)
{
  WCHAR* result;
  if(str == NULL)
    return NULL;
  result = (WCHAR*)malloc(str->Length + 2);
  if(result == NULL)
    // raise?
    return NULL;
  memcpy(result, str->Buffer, str->Length);
  result[str->Length] = L'\0';
  return result;
}
于 2012-03-11T18:25:40.180 回答