Warm tip: This article is reproduced from stackoverflow.com, please click
.net com-interop vb6

Automation Error when instantiating a .Net COM visible class

发布于 2020-04-22 10:39:40

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?!

Questioner
Dabblernl
Viewed
12
Hans Passant 2011-08-29 08:15

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.