I tried to use std::string in WSARecv (winsock), but it didnt work, can you tell me if it's possibleand and how it works
Asked
Active
Viewed 79 times
-4
-
WSARecv requires an array, std::string is not an array. – Michael Chourdakis Apr 05 '19 at 19:32
-
1@michael: not exactly true. Of course a std::string can be an array... – Marco Freudenberger Apr 05 '19 at 19:45
-
1@MarcoFreudenberger prior to C++11, the internal character data of a `std::string` was not *guaranteed* to be stored in contiguous memory, though most common implementations did that. – Remy Lebeau Apr 05 '19 at 22:04
-
@Remy: afaik **ALL** implementations did that, otherwise you couldn't get a valid c string pointer with c_str() without an additional copy operation. Good point though, that it was not strictly guaranteed by the standard. – Marco Freudenberger Apr 06 '19 at 07:10
1 Answers
1
You could initalize your WSABUF structures that you pass to WSARecv, so that the *buf pointer in each WSA buf points to the buffer of a prepared string opbject, something along the lines:
std::string myStringBuffer;
myStringBuffer.resize(1024);
WSABuf wsaBuffer;
wsaBuffer.len = 1024;
wsaBuffer.buf = &myStringBuffer[0];

Marco Freudenberger
- 636
- 6
- 13
-
or `buf = myStringBuffer.data()` in C++17 and later. And I would use `len = myStringBuffer.size()` instead of hard-coding the `len`, in case you want to change the size of `myStringBuffer` later, or make it dynamic. – Remy Lebeau Apr 05 '19 at 22:02
-
@Remy: correct, although `len = myStringBuffer.size()` might need a static_cast to avoid compiler warnings, which is why I didn't mention it. – Marco Freudenberger Apr 06 '19 at 07:08