COM+互操作

來源:互聯網
上載者:User

http://social.msdn.microsoft.com/Forums/en-US/netfx64bit/thread/674cbd6f-8ac7-4902-a7a2-5cc3d831cd5b

http://msdn.microsoft.com/en-us/library/tt0cf3sx%28VS.80%29.aspx

http://technet.microsoft.com/zh-cn/04za0hca.aspx

http://blog.csdn.net/kimmking/article/details/3445233

 

 

ActiveX controls or COM components written in .NET languages cannot be referenced by .NET applications in the

form of interop assemblies. If you "add reference" to such a TLB, or drag & drop such an ActiveX control to your .NET application, you will get an error "The ActiveX type library 'XXXXX.tlb' was exported from a .NET assembly and cannot be added as a reference.". The correct approach is to add a reference to the .NET assembly directly.

 

1       使用C#建立.net的dll1.1    建立項目

在.net中建立一個項目:TestCom。

 

 

1.2    實現c#類

在class1.cs檔案中添加一個介面和一個類:

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

 

namespace TestCom

{

    [ComVisible(true)]

    public interface iClass1

    {

        string test();

    }

 

    [ComVisible(true)]

    [ClassInterface(ClassInterfaceType.AutoDual)]  

    public class Class1 : iClass1

    {

        public string test()

        {

            return "ok";

        }

 

    }

}

 

注意介面和類上的屬性,對com可見和產生com類型。

 

1.3    添加強名

 選擇開始菜單中Vistual Studio目錄下的Vistual Studio Tools下的Vistual Studio 命令提示。使用sn -k c:/myKey.snk產生簽名檔案。

在項目上右鍵,點擊屬性,選擇簽名,選中為程式集簽名,選擇myKey.snk檔案。

 

 1.4    產生解決方案

在項目目錄的/TestCom/bin/Debug中可以找到TestCom.dll。至此,c#產生的.net dll已經完成。

 

 

2       產生和註冊類型庫

 

2.1    產生tlb類型庫

在Visual Studio命令提示字元下,切換到此目錄。

輸入tlbexp TestCom.dll /out:TestCom.tlb,提示成功匯出tlb類型庫檔案。

 

 

 2.2    註冊類型庫

輸入regasm TestCom.dll /tlb: TestCom.tlb /codebase,將類型庫匯入到註冊表。提示成功註冊了類型,說明操作成功,此時TestCom .dll可以作為一個com來使用。

 

 

 2.3    添加dll到GAC

輸入gacutil /i TestCom.dll,將此.net程式集添加到GAC。

 

3       vb調用測試3.1    建立vb項目

在vb中建立一個標準exe項目。

在項目菜單選擇引用,在彈出的引用com對象列表中找到TestCom,選上。

在表單上拖放一個按鈕,雙擊按鈕,在按鈕事件裡輸入代碼:

Dim a As New TestCom.Class1

MsgBox a.test

 

 

 3.2    運行程式

啟動項目,點擊按鈕,彈出對話方塊ok,說明調用成功。

 

 

 

 

4       asp調用測試4.1    建立asp檔案

在iis的根目錄下建立一個文字檔,改名為1.asp,輸入以下內容:

 

<%

SET s = CreateObject("TestCom.Class1")

Response.Write(s.test())

%>

4.2    運行程式

在ie中訪問此檔案,頁面輸出ok,說明調用成功。

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.