Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automation Error when instantiating a .Net COM visible class

I created a COM-interop .dll with this simple class:

using System.Runtime.InteropServices;

namespace ClassLibrary1
{
    [ComVisible(true)]
    [Guid("795ECFD8-20BB-4C34-A7BE-DF268AAD3955")]
    public interface IComWeightedScore
    {
        int Score { get; set; }
        int Weight { get; set; }
}

[ClassInterface(ClassInterfaceType.None)]
[Guid("9E62446D-207D-4653-B60B-E624EFA85ED5")]
public class ComWeightedScore : IComWeightedScore
{

    private int _score;

    public int Score
    {
        get { return _score; }
        set { _score = value; }
    }
    private int _weight;

    public int Weight
    {
        get { return _weight; }
        set { _weight = value; }
    }

    public ComWeightedScore()
    {
        _score = 0;
        _weight = 1;
    }
  }

} I registered it using: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\regasm C:\ComClasses\Classlibrary1.dll /tlb: Classlibrary1.tlb

Finally I succesfully added a reference to the .dll after which VB6 gave me intellisense on the object.

Private Sub Form_Load()
    Dim score1 As ComWeightedScore

    Set score1 = New ComWeightedScore
    score1.Score = 500

End Sub

On the line Set score1=new ComWeightedScore the exception Automation Error is raised.

It can hardly be any simpler than this... Where is the error?!

like image 947
Dabblernl Avatar asked Aug 28 '11 22:08

Dabblernl


3 Answers

You forgot the /codebase option in the Regasm.exe command line.

Without it, you'll have to strong-name the assembly and put it in the GAC with gacutil.exe. Good idea on the client machine, just not on yours.

like image 153
Hans Passant Avatar answered Nov 08 '22 20:11

Hans Passant


If you are running on a 64bit processor with your project compiling as 'CPU-Any' you will either need to compile only for x86 or register the dll in the 64bit COM+ space.

Example of both 32 and 64bit regasm:

%windir%\Microsoft.NET\Framework\v4.0.30319\regasm "Contoso.Interop.dll" /tlb:Contoso.Interop.tlb /codebase Contoso.Interop

%windir%\Microsoft.NET\Framework64\v4.0.30319\regasm "Contoso.Interop.dll" /tlb:Contoso.Interop.tlb /codebase Contoso.Interop

like image 44
Jeremy Avatar answered Nov 08 '22 19:11

Jeremy


I also encountered a similar issue when I ran a generated EXE because I let a local copy of the dll in the VB6 project directory (previously for test purposes).

Running the project in debugging mode (F5) was fine, but the EXE loaded the local dll rather than getting the registred TLB.

Such code below, referencing the interface crashed:

Dim sf As StuffUtils.IStuffer
Set sf = New StuffUtils.Stuffer

Just letting this answer here since it might prevent another coder to waste his time on it.

like image 26
Amessihel Avatar answered Nov 08 '22 21:11

Amessihel