【问题标题】:Convert wstring to WS_STRING将 wstring 转换为 WS_STRING
【发布时间】:2015-02-05 21:52:18
【问题描述】:

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

尝试使用宏:

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

并且有错误:

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

【问题讨论】:

  • 您可能可以const_cast<>自己摆脱麻烦。视情况而定。

标签: visual-c++ wwsapi


【解决方案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

长答案:

不要在WCHAR[] 以外的任何地方使用WS_STRING_VALUE。您可以使用const_cast<> 编译它,但您会遇到两个问题:

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

相关代码sn-ps:

//  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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2011-01-03
    • 2018-01-14
    • 2012-12-12
    • 2012-07-01
    相关资源
    最近更新 更多