MS VC ++ Convert byte array to BSTR?

I have a string that starts in a .Net application, encrypted and stored in AD. It is then picked up by a native C ++ application and decrypted to create an array of bytes eg "ABCDEF" becomes 00,41,00,42,00,43,00,44,00,45 once it has been decrypted at the C + end +.

I need to take this byte array and convert it to BSTR "ABCDEF" so that I can use it elsewhere and I cannot find a way to accomplish this last step.

Does anyone help?

+2


source to share


2 answers


If you do have an array of arbitrary bytes, use SysAllocStringByteLen

. But it looks like even though it is in a byte array, your data is UTF-16 encoded Unicode, so in this case you are probably better off using SysAllocStringLen

. Pass a byte array pointer to a function (type-cast to OLECHAR*

) and the characters will be copied to a new string for you along with an extra null at the end.



+1


source


The "decoded string" is just a Unicode string - Latin characters contain the first byte, which is null if it is in Unicode. This way you don't need any real conversion, just pull the BSTR out of that buffer.



Knowing the number of Unicode characters - this will be half the length of the buffer - a call SysAllocStringLen()

to allocate a long enough uninitialized null terminated BSTR. Then copy the array to the highlighted line with memcpy()

. Alternatively, you can call SysAllocStringLen()

and pass it into a byte buffer so that it will make a copy for you and skip memcpy()

. Remember to call SysFreeString()

when you no longer need BSTR.

0


source







All Articles