[英]Convert wstring to WS_STRING
What is the best way to convert wstring to WS_STRING? 将wstring转换为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 *'
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[]
. 除了WCHAR[]
之外,不要在其他任何东西上使用WS_STRING_VALUE
。 You can get it to compile using const_cast<>
but you will run into two issues: 您可以使用const_cast<>
进行编译,但是会遇到两个问题:
WS_STRING
will have an incorrect length
member due to the macro's use of RTL_NUMBER_OF
instead of looking for null termination. 该WS_STRING
将有一个不正确的length
成员由于宏的使用RTL_NUMBER_OF
,而不是寻找空终止。 WS_STRING
will just reference d
- it will not take a copy. WS_STRING
将仅引用d
不会获取副本。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.