5

The winapi function WinHttpSendRequest() wants the size of the second parameter in the third one and the size of the fourth parameter in the fifth one.
How can I calculate it?
I have a function wrapped around it and I pass the strings directly, about like this:

void Req(LPCWSTR headers, LPVOID body) {
    WinHttpSendRequest( hRequest, headers, (DWORD)strlen(headers), body, (DWORD)strlen(body), 0, 0 );
}
Req(L"User-Agent: blabla/1.0\r\nConnection: Keep Alive", "asdf=qwer&abcd=1234);

The above code doesn't work. :/
I hope you can help me out.

Forivin
  • 14,780
  • 27
  • 106
  • 199
  • `strlen` is for narrow strings, not wide strings. `void *` doesn't have a length to get. I'd recommend taking an actual string for the second parameter, which will convert to `const void *` implicitly if need be. – chris Apr 13 '14 at 18:32
  • How would I convert it to const void *? – Forivin Apr 13 '14 at 18:35
  • It will do that automagically if you take a non-const string, else it will convert to `const void *` instead. Since the function takes a non-const one, it isn't safe to assume it doesn't modify it, and modifying something like a string literal is very bad. You can always take a const string and form a non-const one out of it. And probably use actual C++ strings, which are much more natural to use with your function. – chris Apr 13 '14 at 18:40
  • Please do not use `TCHAR` and its ilk, they are only for porting ancient windows programs. For any communication application, consider going for [UTF-8 everywhere](http://utf8everywhere.org). – Deduplicator Apr 13 '14 at 18:59
  • I tired this now: http://pastebin.com/LkZBJkA0 But even though (DWORD)strlen(body) seems to return the correct size, I get an "invalid parameter" error: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx#error_invalid_parameter – Forivin Apr 13 '14 at 19:09

1 Answers1

8

.You need to use wcslen instead of strlen for wide-strings.

ooga
  • 15,423
  • 2
  • 20
  • 21
  • That seems to work for LPCWSTR! :) DO you know some function like that for LPVOID? – Forivin Apr 13 '14 at 18:50
  • @Forivin: That doesn´t exist – deviantfan Apr 13 '14 at 18:52
  • @Forivin You need to know the actual type of `body` in order to find it's length. If it's also a wide string, then you can either cast it as such in the function, or accept it as such in the function header. – ooga Apr 13 '14 at 19:01
  • 1
    `LPCWSTR` translates to `LPCSTR` if `unicode` is not defined. So if `unicode` is not defined then you will pass `char*` to `wcslen` which accepts `wchar_t*`. https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx – Nishant Dec 02 '16 at 02:58