How to mix std::string with Win32 functions that take char[] buffers?

c++, stl, string, winapi

Solution

`std::string` has a function `c_str()` that returns its equivalent C-style string. (`const char *`)

Further, `std::string` has overloaded assignment operator that takes a C-style string as input.

e.g. Let `ss` be `std::string` instance and `sc` be a C-style string then the interconversion can be performed as :

ss = sc; // from C-style string to std::string
sc = ss.c_str(); // from std::string to C-style string

UPDATE :

As Mike Weller pointed out, If `UNICODE` macro is defined, then the strings will be `wchar_t*` and hence you would have to use `std::wstring` instead.

Problem

There are a number of Win32 functions that take the address of a buffer, such as `TCHAR[256]`, and write some data to that buffer. It may be less than the size of the buffer or it may be the entire buffer. Often you'll call this in a loop, for example to read data off a stream or pipe. In the end I would like to efficiently return a string that has the complete data from all the iterated calls to retrieve this data. I had been thinking to use `std::string` since it's += is optimized in a similar way to Java or C#'s `StringBuffer.append()`/`StringBuilder.Append()` methods, favoring speed instead of memory. But I'm not sure how best to co-mingle the `std::string` with Win32 functions, since these functions take the `char[]` to begin with. Any suggestions?

Original source