I am working on a application which needs to communicate via COM interface with multiple CAD applications (not in the same time). I want to have nice and reusable code, but I came across problems with type casting of COM objects when I made generic application handle getter method.
What I tried so far:
This is the attempt I would like the most if it worked.
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..."); }Attempt using Convert 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." }
I really thought that I am on the right track, since there is an article on Microsoft Docs website explaining how dynamic can help you with com interopt: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic#com-interop
Any ideas how I can do this runtime casting a keep my code as reusable as possible?
My software setup:
- Win 10
- Project is targeted for .NET 4.7.2
- First Tests are with Solidworks 2019
string, which represents ProgID. Return value of Marshal.GetActiveObject is anobjectthat you can cast to any COM interface that it supports. For my case, the interface isSldWorks.SldWorks. More on this on the following link: Marshal.GetActiveObject