Convert wstring to WS_STRING

蓝咒 提交于 2019-12-14 04:09:59

问题


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:

  1. The WS_STRING will have an incorrect length member due to the macro's use of RTL_NUMBER_OF instead of looking for null termination.
  2. The WS_STRING will just reference d - 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!