Working with WinAPI functions that use C-style strings as OUT parameters

Given the WinAPI function that returns it, it is obtained through the OUT parameter of a C-style string, for example:

int WINAPI GetWindowTextW(
   _In_   HWND hWnd,
   _Out_  LPTSTR lpString,
   _In_   int nMaxCount
);

Is there a better way to use the function than what I do below?

HWND handle; // Assume this is initialised to contain a real window handle
std::wstring title;
wchar_t buffer[512];
GetWindowTextW(handle, buffer, sizeof(buffer));
title = buffer;

The above code works, but I have the following problems:

  • The size of the buffer is completely arbitrary, since I cannot find out the length of the string returned by the function. This "feels" wrong for me - I always tried to avoid magic numbers in my code.

  • If the function returns a string that is larger than the buffer, it will be truncated - this is bad!

  • , , , , . , (2), (, 1024 ) -, .

?

0
2

. , , 8. . , , . , . Win32 .

GetWindowTextLength(), , , , (- ).

+3

, Windows API , . , (, GetWindowTextLengthW), , NULL . , .

-- , . , , , GetWindowTextLengthW GetWindowTextW.

, .

std::wstring GetWindowTitle(HWND hwnd) {
    std::wstring title(16, L'X');
    int cch;
    do {
      title.resize(2 * title.size());
      cch = GetWindowTextW(hwnd, &title[0], title.size());
    } while (cch + 1 == title.size());
    title.resize(cch);
    return title;
}

, Windows API. API C, ++. C -, , . ++ , .

+2

Source: https://habr.com/ru/post/1541939/


All Articles