Search code examples
.netvb6interopcom-interop

VB6 .NET Interop Object Required


I know I fixed this same problem about 6 years ago...but I can't quite remember what the trick is.

I have a .NET class. It is COM visible (but not COM registered). It is returned as the result of a call to a COM registered class. So my VB6 code ends up with

Dim instance as Variant
' call .NET exposed tlb to set instance with a COM visible class
Dim wrapper as New ComWrapper  ' this is a .NET class COM exposed and registered
Set instance = wrapper.MyClassInstance ' MyClassInstance is an instance of COM visible, but not COM registered MyClass defined below
instance.DoIt 1

The relevant class is MyClass

public class MyClass
{
    public void DoIt(int id) { ... }
}

Call instance.DoIt 1 throws an exception "Object required". If I remember correctly, it has something to do with the fact that the integer 1 needs to be boxed or unboxed or something, which VB6 doesn't do automatically for you...but I can't remember quite how to fix it... If the method DoIt has no arguments, things work fine...

Anyone know how to fix this one?

Thanks.


Solution

  • It will be a boxed short, VB6 integers are 16 bits. Also, the default argument passing in VB6 is ByRef. Declaring the argument as object ought to work. It has been too long ago, but I think the syntax is wrong. It should be either

    instance.DoIt 1
    

    or

    Call instance.DoIt(1)
    

    Note the parentheses. There's little reason to do this late-bound. As long as your class is [ComVisible] then it will be present in the type library and you can just declare the VB6 variable type to allow the compiler to check your code and generate the most optimal call. Registering the class won't be necessary.

    Dim instance As MyClass