C# 中 COM 对象的运行时转换

Runtime casting of COM objects in C#

我正在开发一个需要通过 COM 接口与多个 CAD 应用程序通信的应用程序(不同时)。我想要漂亮且可重用的代码,但是当我制作通用应用程序句柄 getter 方法时,我遇到了 COM 对象类型转换的问题。

到目前为止我尝试了什么:

  1. 如果成功的话,这是我最想要的尝试。

    public static TCadAppType CadApp<TCadAppType>()
    {
        dynamic cadApp = default(TCadAppType);
    
        //Here under Dynamic View/Message there is already an error
        //  Message = "Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND))"
        // cadVersion.Value evaluates to "SldWorks.Application"
        cadApp = (TCadAppType)Marshal.GetActiveObject(cadVersion.Value);
    
        //Following 2 lines of code are for testing purposes only, i am testing with Solidworks API 
        AssemblyDoc Assembly;
    
        //The exception is thrown when I try to access some method from the Solidworks API 
        Assembly = (AssemblyDoc)cadApp.OpenDoc6("some parametras...");
    
    }
    
  2. 尝试使用转换 class

    // Another attempt using  Convert class
    public static TCadAppType CadApp<TCadAppType>()
    {
        dynamic cadApp = default(TCadAppType);
        // cadVersion.Value evaluates to "SldWorks.Application"
        cadApp = Marshal.GetActiveObject(cadVersion.Value);
    
    
        cadApp = Convert.ChangeType(cadApp, typeof(SldWorks.SldWorks));
        // Exception is thrown with the following message:
        // Message = "Object must implement IConvertible."
    }
    

我真的认为我在正确的轨道上,因为 Microsoft Docs 网站上有一篇文章解释了动态如何帮助您进行 com interopt:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic#com-interop

有什么想法吗我如何才能执行此运行时转换以尽可能保持我的代码可重用?

我的软件设置:

原来我的编码尝试 1 确实是有效的 c# 代码。 我尝试将它与 Autodesk Inventor 一起使用,它确实有效。

所以我唯一剩下的就是得出结论,这是来自 Solidworks 及其 COM 接口的一些错误。

感谢 Optional Option 对该主题的关注。