Converting a fairly simple C# Class library into a COM object?

不羁的心 提交于 2019-12-06 05:13:42

No, that (static/no ctor) isn't true. Quite the opposite, in fact, since COM will need to create an instance! You simply need to make the class COM visible. Mainly, this is just adding some attributes, and registering it as a COM dll (regasm).

http://msdn.microsoft.com/en-us/library/zsfww439.aspx

Creating a class that returns a DataSet is not so difficult:

using System;
using System.Data;
using System.Runtime.InteropServices;

namespace COMTest
{
   [Guid("AC4C4347-27EA-4735-B9F2-CF672B4CBB4A")]
   [ComVisible(true)]
   public interface ICOMTest
   {
       [ComVisible(true)]
       DataSet GetDataSet();
   }

   [Guid("CB733AB1-9DFC-437d-A769-203DD7282A8C")]
   [ProgId("COMTest.COMTest")]
   [ComVisible(true)]
   public class COMTest : ICOMTest
   {
       public DataSet GetDataSet()
       {
           DataSet ds = new DataSet("COMTest");
           return ds;
       }
   }

}

You'll need to check the "Register for COM Interop" box in the Project properties, you'll also need to sign the assembly, and you'll need to make sure that the IIS user can access your bin\Debug directory.

Once you've done this, you can create an instance from ASP just fine:

<%
Dim o
Set o = Server.CreateObject("COMTest.COMTest")
Response.Write("Server.CreateObject worked.")
Response.Write("<br/>")
Dim ds
Set ds = o.GetDataSet()
If Not ds is Nothing Then
  Response.Write("o.GetDataSet returned an object.  Can we use it?")
  Response.Write("<br/>")
  Response.Write("We have a DataSet, and its DataSetName is: ")
  Response.Write(ds.DataSetName)
End If
%>

And here you will be sad. For while the method that returns a DataSet is visible to COM, none of the DataSet's properties or methods are.

Somebody said my class has to be static and I can't have a constructor. Is this true?

A COM class needs to have a default constructor, which will be used by clients when they call CoCreateInstance. After the object is created, you can set properties on it, or call other methods.

This is similar to the way that .Net treats serializable objects... you construct it with a default constructor, then set all its properties. (If you like RAII, you're out of luck with both COM and .Net. Get over it;)

As to the static comment, no, that isn't true, as Marc pointed out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!