Mixing standard C ++ strings and window APIs

Many Windows APIs accept a pointer to a buffer and a size element, but the result should go to a C ++ line. (I use unicode windows here so they are wstrings)

Here is an example: -

#include <iostream>
#include <string>
#include <vector>
#include <windows.h>

using namespace std;

// This is the method I'm interested in improving ...
wstring getComputerName()
{
    vector<wchar_t> buffer;
    buffer.resize(MAX_COMPUTERNAME_LENGTH+1);
    DWORD size = MAX_COMPUTERNAME_LENGTH;

    GetComputerNameW(&buffer[0], &size);

    return wstring(&buffer[0], size);
}

int main()
{
    wcout << getComputerName() << "\n";
}

My question is actually the best way to write the getComputerName function so that it fits better with C ++, or is there a better way? I don’t see the possibility of using the string directly without going through the vector, if I did not miss something? It works great, but somehow it seems a little ugly. The question is not what the specific API is, it is just a convenient example.

+3
source share
4 answers

, std::vector . MAX_COMPUTERNAME_LENGTH , C- .

+7

. StringBuffer, .

+3

, Windows API ++, wstring:

wstring getComputerName()
{
    wchar_t name[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD size = MAX_COMPUTERNAME_LENGTH;

    GetComputerNameW(name, &size);

    return name;
}

wstring.

+2

. , , , , . :

#include <string>
#include <vector>
#include <windows.h>

using std::wstring;
using std::vector;

wstring getComputerName()
{
    DWORD size = 1; // or a bigger number if you like
    vector<wchar_t> buffer(size);
    while ((GetComputerNameW(&buffer[0], &size) == 0))
    {
        if (GetLastError() != ERROR_BUFFER_OVERFLOW) aargh(); // handle error
        buffer.resize(++size);
    };
    return wstring(&buffer[0], size);
}

, , , . , , , std::wstring, , , , MSVC, , .

, wstring::reference - wchar_t&, . 21.3.4 , non-const operator[] a reference data()[pos]. , reference wchar_t&, , &buffer[0]. . , , .

It takes a lot of effort and comments to avoid copying a string, so I never felt the need to avoid an intermediate array / vector.

+1
source

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


All Articles