问题
What is the best way to convert wstring to WS_STRING?
Trying with macros:
wstring d=L"ddd";
WS_STRING url = WS_STRING_VALUE(d.c_str()) ;
And have error:
cannot convert from 'const wchar_t *' to 'WCHAR *'
回答1:
Short answer:
WS_STRING url = {};
url.length = d.length();
WsAlloc(heap, sizeof(WCHAR) * url.length, (void**)&url.chars, error);
memcpy(url.chars, d.c_str(), sizeof(WCHAR) * url.length); // Don't want a null terminator
Long answer:
Don't use WS_STRING_VALUE
on anything other than a WCHAR[]
. You can get it to compile using const_cast<>
but you will run into two issues:
- The
WS_STRING
will have an incorrectlength
member due to the macro's use ofRTL_NUMBER_OF
instead of looking for null termination. - The
WS_STRING
will just referenced
- it will not take a copy. This is obviously problematic if it's a local variable.
The relevant code snippets:
// Utilities structure
//
// An array of unicode characters and a length.
//
struct _WS_STRING {
ULONG length;
_Field_size_(length) WCHAR* chars;
};
// Utilities macro
//
// A macro to initialize a WS_STRING structure given a constant string.
//
#define WS_STRING_VALUE(S) { WsCountOf(S) - 1, S }
// Utilities macro
//
// Returns the number of elements of an array.
//
#define WsCountOf(arrayValue) RTL_NUMBER_OF(arrayValue)
来源:https://stackoverflow.com/questions/27354653/convert-wstring-to-ws-string