當我在g ++上運行此代碼時,它運行平穩,但是當我在Visual Studio上使用unicode字符集選項運行此代碼時,它不會打印產品ID。 你能解釋我如何解決這個問題,爲什麼會發生?爲什麼這段代碼在帶有多字節字符集的visual studio中完美運行,但沒有使用unicode字符集?
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
wchar_t* GetRegistryKeyValue(const char* RegKey, const char* pPIDName)
{
HKEY Registry;
long ReturnStatus;
DWORD regType = 0;
DWORD regSize = 0;
char* pPID = 0;
ReturnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, RegKey, 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &Registry);
if (ReturnStatus == ERROR_SUCCESS)
{
ReturnStatus = RegQueryValueEx(Registry, pPIDName, 0, ®Type, 0, ®Size);
pPID = new char[regSize];
/* Get Value. */
ReturnStatus = RegQueryValueEx(Registry, pPIDName, 0, ®Type, (LPBYTE)pPID, ®Size);
RegCloseKey(Registry);
if (pPID[regSize] > 127 || pPID[regSize] < 32)
{
pPID[regSize] = '\0';
}
if (regSize > 1)
{
int s = 0;
int i=0;
while (pPID[i] != NULL)
{
s++;
i++;
}
const size_t cSize = s ;
wchar_t* wc = new wchar_t[cSize];
mbstowcs(wc, pPID, cSize);
return wc;
}
else
{
printf("Size not > 1 (%d)\n", regSize);
return NULL;
}
}
else
{
RegCloseKey(Registry);
return NULL;
}
}
int main()
{
wchar_t * resultData=NULL;
resultData = GetRegistryKeyValue("SOFTWARE\\MICROSOFT\\Windows NT\\CurrentVersion", "ProductId");
wcout << resultData;
cout << endl;
delete resultData;
system("PAUSE");
return 0;
}
你是幸運的,如果這似乎在所有的工作。在使用'new []'分配的指針上調用'delete'是未定義的行爲。然而,你真正的問題是你重新解釋ANSI編碼的字符串,就好像它們是UTF-16一樣。 – IInspectable
當選擇unicode字符集選項時,prepecasting RegKey和pPID與lpcwstr似乎很好,沒有語法錯誤,但RegQueryValueEx在這種情況下返回2,這不應該發生。 – usamamw141
如果'pPID = new char [regSize]'那麼肯定'pPID [regSize]'超出邊界? – kfsone