How to use BSTR *

I have a value outlike BSTR * for an interface in a C ++ COM dll. And I return this to the C # .Net client. In my C ++ function, I need to assign different values ​​according to the diff condition.

For instance:

If my function is fun(BSTR* outval)
{
   // I have to assign a default value to it such as:
   *outval = SysAllocSTring(L"N");

   Then I will check for some DB conditions
   { 
     // And I have to allocate it according to that.
     // Do I need to again calling SysAllocString?
     eq.*outval = SySAllocString(DBVlaue);
   }
}

What happens if I call SysAllocSTring twice in the same BSTR? What is the best way to handle this?

+5
source share
4 answers

You should take care of everything BSTRexcept those that you actually pass as the "out" parameter. BSTRyou cannot free yourself - the caller is responsible for freeing him, and your code is responsible for all the others BSTRthat he could allocate.

BSTR, -, ATL::CComBSTR _bstr_t BSTR ( , ). , , , , BSTR .

:

 HRESULT YourFunction( BSTR* result )
 {
     if( result == 0 ) {
         return E_POINTER;
     }
     int internalStateValue = getState();
     if( internalStateValue > 0 ) { // first case
         *result = SysAllocString( "positive" );
     } else if( internalStateValue < 0 ) { //second case
         *result = SysAllocString( "negative" );
     } else { //default case
         *result = SysAllocString( "zero" );
     }
     return S_OK;
  }
+8

, , CComBSTR , BSTR.

BTW, CComBSTR RAII

+3

If you call SysAllocString twice, you will skip the first BSTR. You must not do this. Instead, you can instead SysFreeString on the first BSTR and then on SysAllocString or simply call SysReAllocString to redistribute the existing BSTR value.

Martyn

+2
source

If you use the function:

HRESULT Foo(BSTR input){...}

Call it like this:

Foo(_bstr_t(L"abc"));
0
source

All Articles