Connecting Tech Pros Worldwide Help | Site Map

C# string[] to VARIANT* for COM

Newbie
 
Join Date: Jul 2008
Posts: 1
#1: Jul 17 '08
Hello,
I have the following COM definition, which supposedly takes in a vector of strings.
************** IDL *************************
[id(1), helpstring("method myMethod")]
HRESULT myMethod( [in] VARIANT* bFlags, [out,retval] VARIANT* result);
************** IDL *************************

I Have an example using C++ where the method is called

***************** C++ *******************
Expand|Select|Wrap|Line Numbers
  1. void
  2. initComVariantArray( const std::vector<std::string>& inputFlags,
  3.                      CComVariant& rOutputFlags )
  4.                      throw ( _com_error )
  5. {
  6.     rOutputFlags.ChangeType( VT_VARIANT );
  7.  
  8.     CComSafeArray<VARIANT> inputArray( (ULONG) 0 );
  9.     for ( unsigned int i = 0; i < inputFlags.size(); ++i )
  10.     {
  11.         CComVariant comPacsKey;
  12.         CComBSTR tmpString( inputFlags[i].c_str() );
  13.  
  14.         // The operator= will set automatically the type to VT_BSTR
  15.         comPacsKey = tmpString;
  16.  
  17.         HRESULT hr = inputArray.Add( comPacsKey );
  18.         if ( FAILED( hr ) )
  19.         {
  20.             throw _com_error( hr );
  21.         }
  22.     }
  23.  
  24.     // The operator= will add automatically the type VT_ARRAY to the vt
  25.     rOutputFlags = inputArray;
  26. }
  27.  
  28. Main():
  29. {
  30. CComVariant vFlags;
  31. vector<string> vecFlags(); vecFlags.push_back( "flag1" );
  32. initComVariantArray( vecFlags, vFlags );
  33. CComVariant vResult = pInteface->myMethod( (&vFlags );
  34. }
  35.  
***************** C++ *******************

This works great with C++, but i can't get the interface to work in C#. when i import the interface into C#, i get the following definition:

*************** C# ************************
Expand|Select|Wrap|Line Numbers
  1. myMethod( ref object );
  2.  
  3. and calling the method as:
  4. string [] flags = { "flag1" };
  5. object objFlag = ( object ) flags;
  6. myMethod( ref objFlag );
Does not work. I get the exception:
System.Runtime.InteropServices.SEHException: External component has thrown an exception.
*************** C# ************************

If you guys know what im doing wrong here, it would be a lot of help.

Thanks in advance.
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,156
#2: Jul 17 '08

re: C# string[] to VARIANT* for COM


It says external component threw an exception. What exception did the external(com) component throw?
Reply