I tested it quickly and it works without any problems
if you follow the manual page:
https://docs.microsoft.com/de-de/windows/win32/api/sysinfoapi/nf-sysinfoapi-getcomputernameexa
There are several problems with the code above.
1. The buffer size has a fixed size, although the true size is unknown.
What happens if the buffer is not sufficient?
There is actually only one sensible solution here if you do not know the length.
You must first determine the length and then allocate memory appropriately for it.
Here you should remember that the terminating 0 also has space at the end of the string.
The alternative with a pointer to allocated memory and a length like from CPallini and Dave Kreskowiak would
of course also work. But then you would have to double the effort. Once in the DLL and once when called.
2. The first parameter of GetComputerNameExA() should have a value defined in COMPUTER_NAME_FORMAT.
3. I would avoid copying the buffer.
4. There is no harm in providing a return value.
My test program now looks like this:
#define LIBRARY_API __declspec(dllimport)
extern "C" LIBRARY_API BOOL GetName(char **nbuf, DWORD *len);
extern "C" LIBRARY_API BOOL GetName2(char *nbuf, DWORD *len);
#pragma comment( lib, "mydll")
int main()
{
char *nbuf;
DWORD len;
BOOL rtn = GetName( &nbuf, &len);
if(len>0) {
std::cout << "Hostname is: " << nbuf << "\n";
free(nbuf);
}
return 0;
}
Or, when you are sure, that you want it:
int main()
{
char nbuf[MAX_COMPUTERNAME_LENGTH + 1];
DWORD len = sizeof(nbuf);
BOOL rtn = GetName2(nbuf, &len);
if (rtn != 0) {
std::cout << "Hostname is: " << nbuf << "\n";
}
return 0;
}
The source of dll looks like this
#define LIBRARY_API __declspec(dllexport)
extern "C" LIBRARY_API BOOL GetName(char **nbuf, DWORD *len)
{
*len = 0;
DWORD length = 0;
BOOL ok = GetComputerNameExA(ComputerNameDnsHostname, NULL, &length);
...
return ok;
}