How to convert char * to BSTR?

后端 未结 5 1273
滥情空心
滥情空心 2020-12-03 01:51

How can I pass a char * from C dll to VB

Here is sample code:

void Cfunc(char *buffer,int len)
{
  BSTR buf_bstr = SysAllocString((BSTR)buffer);
  V         


        
5条回答
  •  有刺的猬
    2020-12-03 02:18

    Call MultiByteToWideChar(), then either SysAllocString() or SysAllocStringLen().

    Don't forget to call SysFreeString() when you no longer need the BSTR.

    In detail (SysAllocStringLen() variant – it's shorter and faster):

    1. Call MultiByteToWideChar() and pass 0 as fifth and sixth parameters. It will return the number of characters in the Unicode equivalent of the ANSI string. Remember, ANSI string can contain whatever characters, not only ASCII, so any attempts to manually calculate the number of Unicode characters given the ANSI string length may work in some cases and not work in others.

    2. Allocate a buffer for the BSTR with SysAllocStringLen(). Pass 0 as the first parameter and the number of Unicode characters as the second parameter. You now have a properly allocated but uninitialized BSTR. It already has place for the trailing zero and this trailing zero is properly placed.

    3. Call MultiByteToWideChar() second time and this time pass the allocated BSTR there. The function will convert the string into Unicode and copy the result into the BSTR. Now you have a propely allocated BSTR containing the Unicode equivalent of your ANSI string.

    4. Pass the BSTR into VB. Enjoy.

    5. Call SysFreeString() to deallocate the BSTR.

提交回复
热议问题