views:

28

answers:

1

Hello

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

+1  A: 

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;
}
Sam
There's also `SysAllocStringLen` to avoid the null-terminated copy
Rup
Thanks for your reply. But i don't have it as a pointer variable. I've it as PUNICODE_STRING _variable. How to convert it now? Pardon me if it is a dumb question. I'm entirely new to VC++ and Win32 API.
NLV
Change the first line to `(PUNICODE_STRING pStr)` - no star - and change all the `pStr.` to `pStr->` - that ought to work. Maybe also change `BSTR* bstrString` to just `BSTR bstrString`. Alternatively the one-liner `BSTR bstrString = ::SysAllocStringLen(pStr->Buffer, pStr->Length)` ought to work too.
Rup
Thanks for your comment Rup. Will try it and let you know.
NLV
Yes, Rup's one-liner does the job nicely! I'll edit up my code so that it is correct for future generations.
Sam
Thanks Sam and Rup. Works great. @Sam have a small typo in the code. In memset(nullTerminatedString, 0, sizeof(wchar_t) * (pStr->Length + 1)); it should be a closing paranthesis instead of a closing square bracket at the end :).
NLV

related questions