December 20, 2007

Calling COM object methods with extra parameters from C#

I am working on an ASP.NET app that is calling existing COM objects. A wrapper for the COM objects has been created using tlbimp, and that wrapper is referenced in my project.

One of the issues I am seeing is that the method signatures are occasionally different when calling the bridge in C# than in the sample classic ASP code that calls the same objects. One good example is with the Add method on VBA.Collection.

In classic ASP, you can simply call [class].[VBA.Collection].Add("mystring"). However, when calling the bridge in C#, the signature for this method shows up as [class].[VBA.Collection].Add(ref item, ref key, ref Before, ref After). No overloads, this is the only signature available. The actual parameter you want to use is the first one: "item", but what values/types do you pass for these parameters to make the equivalent call?

For the actual value you want to pass, you'll need to create a variable of type object to pass by ref into the first (item) parameter:

object item = "texttext";

for the other three, I tried passing various values, nulls, and types with no success, failing sometimes compile time, sometimes run time:

Exception from HRESULT: 0x800A0005 (CTL_E_ILLEGALFUNCTIONCALL)

the answer is to use System.Reflection.Missing.Value to represent the missing parameters. The called object will now use the default parameter values for key, Before, and After, and successfully add your item to the collection. Here's the code:

object m = System.Reflection.Missing.Value;
object name = "testtext";

oCOMClass.VBACollectionProperty.Add(ref name, ref m, ref m, ref m);

Share |

4 comments:

  1. Great tip! You saved me a ton of work.

    ReplyDelete
  2. great tip - I was just searching through what other values I could pass through, after getting the same errors when passing nulls. Many thanks

    ReplyDelete
  3. great tip - I was just searching through what other values I could pass through, after getting the same errors when passing nulls. Many thanks

    ReplyDelete
  4. thanks a lot for this gr8 tip

    ReplyDelete