首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 建立 COM 物件(一):專案建立、介面定義、Guid 與 DispId 規範

     編輯:關於C語言

目標與前置條件

  • 使用 C# 建立簡單 COM 物件 (COM Interop)
  • 從 VC++ 用戶端透過類型庫 (.TLB) 存取
  • 測試資料庫:SQL Server Northwind
  • 修改 COM 物件中 SQL Server 名稱以連線
  • 預設帳號 scott/tiger 或現有帳號

建立類別庫專案

VS.NET → 檔案 → 新增專案 → Visual C# 專案 → 類別庫,命名 Database_COMObject。

COM 可見性需求

  • 類別必須為 public
  • 屬性、方法、事件必須為 public
  • 屬性與方法必須在類別介面定義
  • 事件必須在事件介面定義
  • 未在介面定義的 public 成員僅 .NET 可見,COM 不可見

介面定義規範

每個介面需 Guid 屬性 (用 guidgen.exe 產生註冊表格式)。成員須標記 DispId,順序即 COM 中順序。

類別介面

[Guid("694C1820-04B6-4988-928F-FD858B95C880")]
public interface DBCOM_Interface
{
    [DispId(1)] void Init(string userid, string passWord);
    [DispId(2)] bool ExecuteSelectCommand(string selCommand);
    [DispId(3)] bool NextRow();
    [DispId(4)] void ExecuteNonSelectCommand(string insCommand);
    [DispId(5)] string GetColumnData(int pos);
}

事件介面

[Guid("47C976E0-C208-4740-AC42-41212D3C34F0"),
 InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface DBCOM_Events { }

類別定義與屬性

[Guid("9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E"),
 ClassInterface(ClassInterfaceType.None),
 ComSourceInterfaces(typeof(DBCOM_Events))]
public class DBCOM_Class : DBCOM_Interface { }

類別前必須設定 ClassInterface(ClassInterfaceType.None) 與 ComSourceInterfaces(typeof(DBCOM_Events))。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved