Use an std::string
to avoid memory issues. And as std::string
uses single byte characters, you should use the single-byte version of GetComputerNameEx
, GetComputerNameExA
.
Also it is a good idea to check the error value, as the documentation explicitly states that the computer name might be longer than MAX_COMPUTERNAME_LENGTH.
std::string getName()
{
char buffer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD length = sizeof(buffer);
bool ok = GetComputerNameExA((COMPUTER_NAME_FORMAT)0, buffer, &length);
if (ok) {
return buffer;
} else {
//handle error
}
}
Or you can use the wide version:
std::wstring getName()
{
wchar_t buffer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD length = sizeof(buffer) / sizeof(wchar_t);
bool ok = GetComputerNameExW((COMPUTER_NAME_FORMAT)0, buffer, &length);
if (ok) {
return buffer;
} else {
//handle error
}
}
or make a code that works under both environments (idea from here):
std::basic_string<TCHAR> getName()
{
TCHAR buffer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD length = sizeof(buffer) / sizeof(TCHAR);
bool ok = GetComputerNameEx((COMPUTER_NAME_FORMAT)0, buffer, &length);
if (ok) {
return buffer;
} else {
//handle error
}
}