zwierzak
zwierzak

Reputation: 269

How to convert LPWSTR to LPBYTE

I found many informations how to convert LPBYTE to LPWSTR, but no info about reverse process. I have tried do it on my own and tested such methods:

// my_documents declaration:
WCHAR my_documents[MAX_PATH];
//1st
const int size = WideCharToMultiByte(CP_UTF8, 0, my_documents, -1, NULL, 0, 0, NULL);
char *path = (char *)malloc( size ); 
WideCharToMultiByte(CP_UTF8, 0, my_documents, -1, path, size, 0, NULL);
//2nd
size_t i;
char *pMBBuffer = (char *)malloc( MAX_PATH );
cstombs_s(&i, pMBBuffer, MAX_PATH, my_documents, MAX_PATH-1 );

But when I write them to registry they are unreadable. And this is how I write them to registry:

BOOL SetKeyData(HKEY hRootKey, WCHAR *subKey, DWORD dwType, WCHAR *value, LPBYTE data, DWORD cbData)
{
    HKEY hKey;
    if(RegCreateKeyW(hRootKey, subKey, &hKey) != ERROR_SUCCESS)
        return FALSE;
    LSTATUS status = RegSetValueExW(hKey, value, 0, dwType, data, cbData);
    if(status != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        return FALSE;
    }
    RegCloseKey(hKey);
    return TRUE;
}

SetKeyData(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", REG_SZ, L"My program", (LPBYTE)path, size)

There is no problem with conversion, but when I try to write this to registry I get some strange chars

Upvotes: 0

Views: 1678

Answers (1)

Anders
Anders

Reputation: 101746

When you are writing a string to the wide registry functions you should not convert but pass a normal WCHAR*, just cast to LPBYTE. Just remember to get the size correct. LPBYTE is really for when you write a binary blob, every other type has to be casted...

Upvotes: 2

Related Questions