tags:

views:

174

answers:

4
char lpszUsername[255];
DWORD dUsername = sizeof(lpszUsername);
GetUserNameA(lpszUsername, &dUsername);
ret_status = NetUserGetInfo(pc_name, lpszUsername, 1, (LPBYTE*)&ui);

So I need char for GetUserNameA, but for NetUserGetInfo - LPCWSTR. WTF? How do I can convert char to this?

error C2664: 'NetUserGetInfo' : cannot convert parameter 2 from 'char [255]' to 'LPCWSTR'
A: 

See MSDN for the relevant conversion macros:

#include <AtlBase.h>

USES_CONVERSION;

char lpszUsername[255];
DWORD dUsername = sizeof(lpszUsername);
GetUserNameA(lpszUsername, &dUsername);

// A2W() should do it
ret_status = NetUserGetInfo(pc_name, A2W(lpszUsername), 1, (LPBYTE*)&ui);
egrunin
error C3861: 'A2W': identifier not found
Loderunner
Added `#include <atlbase.h>`
egrunin
+2  A: 

LPCWSTR translates to english as: "Wide-character string", or wchar_t* in C.

To convert an ascii string to a wide-character string, you may need a special conversion function.

mbstowcs() may be what you need.

Alexander Rafferty
technically isn't it "long pointer to wide-character string"?
jay.lee
"far read-only pointer to zero-terminated sequence of wide characters". The pointer itself can be reassigned, but it can only be used to read the wide characters, not change them. And in Win32's flat memory model there is no difference between near and far pointers.
Ben Voigt
I gave the simple version.
Alexander Rafferty
+1  A: 

Consider using GetUserNameW instead of GetUserNameA. This will give you the current user's name in a wide-character string, eliminating the need to convert from ANSI to Unicode.

WCHAR lpwszUsername[255];
DWORD dUsername = sizeof(lpwszUsername) / sizeof(WCHAR);
GetUserNameW(lpwszUsername, &dUsername);
ret_status = NetUserGetInfo(pc_name, lpwszUsername, 1, (LPBYTE*)&ui);
Nick Meyer
Even better, use `GetUserNameW` to avoid depending on a macro.
dan04
@dan, but then if Loderunner tries to compile for ANSI, this will break the opposite way (needing to convert a wide-character string to an ANSI string). What's wrong with depending on a macro? It's a well-documented part of the Windows API, and extremely unlikely to change.
Nick Meyer
@dan, ah, nevermind. I missed the part that NetUserGetInfo only has a wide-character version. Editing...
Nick Meyer
A: 

I think Nick Meyer's answer solves your problem. But in general i found the following solution easiest for converting LPCSTR to LPCWSTR.

copy LPCSTR to a std::string. initialize a std::wstring with the std::string. get the LPCWSTR from c_str() of std::wstring.

Abhinay K Reddyreddy