I have the following C++ code that retrieves header request information from an HttpContext instance:
public: REQUEST_NOTIFICATION_STATUS OnBeginRequest( IN IHttpContext * pHttpContext, IN IHttpEventProvider * pProvider ) { UNREFERENCED_PARAMETER(pHttpContext); UNREFERENCED_PARAMETER(pProvider); PCSTR header = pHttpContext->GetRequest()->GetHeader("Accept", NULL); WriteEventViewerLog(header); As you can see, the call:
pHttpContext->GetRequest()->GetHeader("Accept", NULL)** Returns a PCSTR data type.
But I need to feed the WriteEventViewerLog with header as a "LPCWSTR", since one of the functions that I use inside the methods only accepts the string in that format.
From https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx, about these string definitions:
A pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef CONST CHAR *PCSTR;
And LPCWSTR:
A pointer to a constant null-terminated string of 16-bit Unicode characters. For more information, see Character Sets Used By Fonts.
This type is declared in WinNT.h as follows:
typedef CONST WCHAR *LPCWSTR;
I didn't find out a way of converting from these two data types. I tried casting header to char* and then using the function below to move from char* to LPCWSTR:
LPWSTR charArrayToLPWSTR(char *source) { // Get required buffer size in 'wide characters' int nSize = MultiByteToWideChar(CP_ACP, 0, source, -1, NULL, 0); LPWSTR outString = new WCHAR[nSize]; // Make conversion MultiByteToWideChar(CP_ACP, 0, source, -1, outString, nSize); return outString; } But that returned to me an invalid string (I don't have the complete input, but the Accept header value was trimmed to "x;ih").
charArrayToLPWSTR()should work, though I'd make itconst char *sourceto match the type ofPCSTR:LPWSTR wszHeader = charArrayToLPWSTR(header); /* Code using wszHeader. */ delete[] wszHeader;. Do you have more information such as sample input and output that works or doesn't work and maybe the actual section of code that requires usage ofLPWSTR?CP_UTF8instead ofCP_ACPMultiByteToWideChar(), or write some function returning aCStringorstd::wstring, but do not return a raw owning pointer allocated withnew[]inside the function body. This can be a leaktrocity if the caller doesn't pay much attention to deallocate the returned string. It's C++, not C.