Search code examples
visual-c++stringcom-interop

How to convert PUNICODE_STRING to bstr?


I'm calling a function which is in a ComVisible managed dll from a VC++ code. In the managed dll the function parameter type is string.

In the VC++ code i've the variable as PUNICODE_STRING. How can i pass it to the function? How can i convert it into BSTR?

Thank you.

NLV


Solution

  • The first thing to note is that PUNICODE_STRING's internal string buffer might not be null-terminated. So it would be best to go via a standard null-terminated wide string, that can then be passed straight to SysAllocString.

    Try this:

    BSTR PUNICODEToBSTR(PUNICODE_STRING pStr)
    {
        // create a null-terminated version of the input string
        wchar_t* nullTerminatedString = new wchar_t[pStr->Length + 1];
        memset(nullTerminatedString, 0, sizeof(wchar_t) * (pStr->Length + 1)];
        wcsncpy(nullTerminatedString, pStr->Buffer, pStr->Length);
    
        // create a BSTR
        BSTR bstrString = ::SysAllocString(nullTerminatedString);
    
        // tidy-up and return the BSTR
        delete [] nullTerminatedString;
        return bstrString;
    }