String in WinAPI and C ++ I / O

I teach my own WinAPI in C ++, but as I progress, I notice that every function in WinAPI returns either char *, DWORD, LPCSTR, etc. I am worried about using a string, so what I do after getting the return value is I convert it to a string. Is it good or bad? or does it matter if I convert it every time? or it will make the process slow or any bad things. And for I / O in C ++, which is better than cout or printf, given the exe size or performance / functionality issues?

+4
source share
2 answers

Start by exploring the different types of strings. For example, char*, LPSTRand LPCSTRare connected with each other and retain ANSI symbols; the latter is a pointer to a constant string. Similarly wchar_t*, WCHAR*, LPWSTRand LPCWSTRare connected and stored Unicode characters; again, the last is a pointer to a constant string.

Then look what you mean when you say something like “returns char *”, since most Windows APIs do nothing. Instead, they take LPSTR(a pointer to a char buffer) or LPWSTR(a pointer to a WCHAR buffer) and write to the buffer. These APIs again almost always take the number of characters available in the buffer, or have document buffer size requirements such as MAX_PATH.

. ++ 11 , a std::wstring std::string , . , API, GetEnvironmentVariable, . , , , :

std::wstring GetEnvironmentVariable(const std::wstring& strName)
{
    DWORD cchValue = MAX_PATH;
    std::wstring strValue;

    // call API once or twice, to get required buffer size
    strValue.resize(cchValue);
    cchValue = GetEnvironmentVariable(strName.c_str(), &strValue[0], cchValue);
    if (cchValue > MAX_PATH)
    {
        strValue.resize(cchValue);
        cchValue = GetEnvironmentVariable(strName.c_str(), &strValue[0], cchValue);
    }

    // process errors such as ERROR_ENVVAR_NOT_FOUND
    if (0 == cchValue)
    {
        // throw exception? return empty string? (current code does latter)
    }

    // remove null character and any extra buffer
    strValue.resize(cchValue);
    return strValue;
}

, .

  • Windows 9x, LPTSTR , typedef tstring, std::wstring std::string UNICODE ( ' d , ). A W, ++, Windows.
  • , - , , .
  • API-, in-out .
  • API-, GetWindowText, /, , . . answer . ( , ).

-, . , - Windows, , , . , , ; , , , iostream. , .

+2

, , . , char *, std::string, , . , , , . std::string, , API ( .) , . , , char *, new malloc std::string, , .

printf std:: cout. , . std:: cout , , .

+1

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


All Articles