Search code examples
visual-c++wwsapi

Convert wstring to WS_STRING


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 *'  

Solution

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