Use HRESULT_FROM_WIN32.

Share
 

Here is a sample to create an array of BSTR’s…

const long lCount = 100;
_bstr_t bstrArray[lCount];

COleSafeArray cosaSafeArray;
cosaSafeArray.CreateOneDim( VT_BSTR, lCount )

// Fill out this array
for( long lIndex = 0; lIndex < lCount; ++lIndex )
{
  cosaSafeArray.PutElement( &lIndex,
			 static_cast<bstr>( bstrArray[lIndex] );
}

// Now you have a safe array of bstr's and since COleSafeArray
// is inherited from VARIANT you can directly use this safearray
// in COM calls with no overhead for freeing safe array
Share
 

Use StringFromCLSID and CLSIDFromString.

Share
 

To enable the use of CLSID_MyClsid/IID_ISomeInterface while importing type libraries use…

#import "MyTypeLib.tlb" named_guids
Share
 

When importing a type library it could be at times cumbersome to use the default namespace name.

#import provides a nice option called rename_namespace.

Use…

#import "SomeTypelib.tlb" rename_namespace( "NibuNamespace" )

Using no_namespace is lazy programming :| . Namespaces reduces name collision hence usage should be encouraged.

Share
 

Sometime back I was wondering about whether there was a way to transfer our good ol’ NULL terminated strings using COM apart from using BSTR’s.

That’s how I bumped into “string” attribute provided by MIDL.

Here is how we use it…

typedef [string] char NormalString[1024];

[id(1), helpstring( "Displays null terminated UNICODE strings" )]
HRESULT ShowMsgUnicodeString( [in,string] wchar_t* wCharString_i );

[id(2), helpstring( "Displays null terminated ANSI strings" )]
HRESULT ShowMsgAnsiString( [in,string] char* cString_i );

Well if we don’t specify “string” then MIDL treats the parameter as an address of a wchar/char.

Callers can invoke the call as they would normally do with a function.

Share
 

Easiest way to construct a COM interface from it’s co class.

ISomeInterfacePtr sipPtr;
HRESULT hRes =
CComCreator< CComObject< CSomeCoClass > >::CreateInstance( 0,
                                                           IID_ISomeInterface,
                                                           reinterpret_cast( void**, &sipPtr ));

ASSERT( SUCCEEDED( hRes ));

Must be an ATL/COM Project.

Share
© 2012 bits and bytes Suffusion theme by Sayontan Sinha