简体   繁体   中英

How much consistency is there with WinAPI functions that have string out parameters?

I have recently begun to write in C on Windows and have been trying to be careful with the different ways that string buffers are handled. For instance, GetWindowText() takes an int nMaxCount of the maximum number of characters, including null. GetModuleFileName() takes a DWORD nSize of the size of the buffer, in TCHARs (I assume this also includes null). Even though these are worded differently and one takes a DWORD while the other takes an int (why the difference in types?), the behavior is identical, correct?

Both return the length of the string that is copied, not including the null, so I should be able to call either of them repeatedly, doubling the buffer size until the returned length is less than the buffer size passed in, like this:

DWORD buf_size = 1024;
DWORD return_val;
wchar_t *full_path = malloc(buf_size * sizeof(wchar_t));

// double the buffer until it's big enough
while ((return_val = GetModuleFileNameW(NULL, full_path, buf_size)) == buf_size) {
    buf_size *= 2;
    full_path = realloc(full_path, buf_size * sizeof(wchar_t));
}

if (!return_val) {
    fprintf(stderr, "Error in GetModuleFileNameW()\n");
    return NULL;
}

Do all of the Windows API functions with string [out] parameters work in the same way? Are there any individual functions or groups of functions that behave differently? (for instance, functions that take the size of the buffer in bytes instead of characters, or that take a maximum string length not including the null character or that return a different value than these two)

Actually, I just noticed that the return value of these two is not entirely consistent: GetModuleFileName() returns 0 when it errors; GetWindowText() will return 0 whenever there is an empty string for the window text, which I think I saw quite frequently when I was enumerating windows...

One reason I want to understand it in detail is because in some cases ( GetModuleFileName() on WinXP, for instance), an off-by-one error in my code will result in a string that is not null-terminated.

By and large the majority of the Win32 API functions that return strings do so in a consistent manner. GetWindowText is a good choice for a canonical such function. However, there are exceptions, and I don't think anyone has ever compiled a comprehensive list.

The bottom line here is that you need to consult the documentation carefully every single time you write code to call a Win32 API function. Not only regarding the treatment of string output values, but all parameters. And all return values. And error handling. There is variation in style across the API, and even variation within related groups of functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM