-1

I have two functions! The first one is

GetUserName(LPSTR buffer, LPDWORD size);

And

SetInfo(LPCWSTR user, int secret);

I have to take the output from GetUserName which is buffer as an LPSTR

Then I have to use that string in the SetInfo function as an LPCWSTR

My question is; What is the safest and best approach to doing this?

Can MultiByteToWideChar be used here? Thanks!

user3251225
  • 147
  • 3
  • 11

2 Answers2

3

If the GetUserName function is the Windows API function then you can just explicitly call the wide version:

wchar_t buffer[100];
GetUserNameW(buffer,100);
Sean
  • 60,939
  • 11
  • 97
  • 136
3

The proper way to call many Windows API is to make a first call supplying an empty buffer and requesting the size. Then allocate the buffer and make the call.

Here is an example for GetUserNameW.

DWORD size = 0;
wstring name;

auto ret = GetUserNameW(nullptr, &size);
if(!ret && ERROR_INSUFFICIENT_BUFFER == ::GetLastError() && size > 0)
{
   wstring.resize(size);
   ret = GetUserNameW(&name[0], size);
}
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91