簡體   English   中英

我可以只公開某些 C# 類嗎?

[英]Can I make only certain C# classes COM-exposed?

我有一個 C# 庫項目,該項目旨在通過 COM 從非托管 C++ 代碼中使用。 在此處輸入圖像描述

只會以這種方式調用 2 或 3 個方法,但我會收到如下警告:

警告:類型庫導出器警告處理''。 警告:類型庫導出器在簽名中遇到泛型類型實例。 通用代碼可能無法導出到 COM。

這些屬性和方法並非設計用於從 C++ 訪問,事實上它們甚至不是public方法,因此它們(肯定)無論如何都不可見。

真的有兩個問題:

  • Q1:如何控制導出的內容? 類/方法或其他東西的訪問修飾符?
  • Q2:我如何查看導出的內容,例如檢查類型庫中的內容,看看我是否遺漏了什么

最好仔細檢查一下我沒有用大量不應該存在的東西來膨脹我的類型庫......

我可以聲明整個程序集對 COM 不可見,就像這樣(實際上,當您使用 Visual Studio C# class 庫模板時,它應該將它自己放在 AssemblyInfo.cs 中):

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

現在,在每個 class 中,我可以決定 COM 是否可以看到它,或者不像這里:

using System;
using System.Runtime.InteropServices;

namespace ClassLibrary1
{
    [ProgId("MyCoolClass")]
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class MyCoolVisibleClass
    {
        public void SayHello()
        {
            Console.WriteLine("Hello COM world");
        }

        // explicit non COM visible because it's set to true at class level
        [ComVisible(false)]
        public void SayHello2()
        {
            Console.WriteLine("Hello world");
        }
    }

    // implicit non COM visible
    public class MyCoolInvisibleClass
    {
        public void SayHello()
        {
            Console.WriteLine("Hello world");
        }
    }
}

您可以使用項目屬性進行注冊(“注冊 COM 互操作”復選框),但我個人使用這樣的命令行注冊自己(對於 64 位注冊表世界):

%windir%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe ClassLibrary1.dll /codebase /tlb

這會輸出如下內容:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe ClassLibrary1.dll /codebase /tlb
Microsoft .NET Framework Assembly Registration Utility version 4.8.3752.0
for Microsoft .NET Framework version 4.8.3752.0
Copyright (C) Microsoft Corporation.  All rights reserved.

RegAsm : warning RA0000 : Registering an unsigned assembly with /codebase can cause your assembly to interfere with other applications that may be installed on the same computer. The /codebase switch is intended to be used only with signed assemblies. Please give your assembly a strong name and re-register it.
Types registered successfully
Assembly exported to 'D:\KilroyWasHere\ClassLibrary1.tlb', and the type library was registered successfully

我可以使用Windows SDK 中的 OleView檢查 .tlb 中的真正內容:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM