0

将 wstring 转换为 WS_STRING 的最佳方法是什么?

尝试使用宏:

wstring d=L"ddd";
WS_STRING url = WS_STRING_VALUE(d.c_str()) ;

并有错误:

cannot convert from 'const wchar_t *' to 'WCHAR *'  
4

1 回答 1

1

简短的回答:

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

长答案:

不要用于WS_STRING_VALUE除 a 以外的任何东西WCHAR[]。您可以使用它来编译它,const_cast<>但您会遇到两个问题:

  1. 由于宏的使用而不是寻找空终止,WS_STRING将有一个不正确的成员。lengthRTL_NUMBER_OF
  2. WS_STRING只是参考d- 它不会复制。如果它是一个局部变量,这显然是有问题的。

相关代码片段:

//  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)
于 2015-01-16T01:00:27.140 回答