Wrapping a COM object/dynamic type in C#

2019-03-01 00:57发布

I am currently working with COM objects in managed code and am using the new dynamic type for this. This works well in some areas but can be an issue in others.

I was think about how I could get the best of both worlds, the flexibility of the dynamic type (late bound) with the support for say, an RCW (early bound)

Somehow wrapping the dynamic type in a more manageable stucture. I was wondering if there was a preferred method for this (if it is even a good idea) or what things I should consider.

The two basic ideas I came up with so far as follows:

Firstly, creating a static class that allows me to call the methods of the dynamic type in a managed way.

public static class ComObjectWrapper
{
   public static void SomeMethod(dynamic comObject, int x)
   {
      comObject.someMethod(x);
   }

   public static bool GetSomeProp(dynamic comObject)
   {
      comObject.getSomeProp();
   }

   public static void SetSomeProp(dynamic comObject, bool foo)
   {
      comObject.setSomeProp(foo);
   }
}

Secondly, creating a class that is constructed using the com object, then mapping all its members to managed properties, methods, etc.

public class ComObjectWrapper
{
   private dynamic comObject = null;

   public ComObjectWrapper(dynamic comObject)
   {
     this.comObject = comObject;
   }

   public void SomeMethod(int x)
   {
      comObject.someMethod(x);
   }

   public bool SomeProp
   {
      get
      {
         return comObject.getSomeProp();
      }
      set
      {
         comObject.setSomeProp(value);
      }
   }
}

Are there other ways to approach this? Am I missing something stupid!?

1条回答
forever°为你锁心
2楼-- · 2019-03-01 01:50

The opensource framework Impromptu-Interface will wrap a dynamic object with a static interface such that all the statically defined members from the interface use the dlr to forward to the dynamic object.

Create Your interface

IComObjectWrapper
{
   void SomeMethod(int x);
   bool SomeProp;
}

Then where you need to wrap your com object include ImpromptuInterface

  using ImpromptuInterface;

And finally to wrap it:

var tStaticTyped = Impromptu.ActLike<IComObjectWrapper>(comObject);
查看更多
登录 后发表回答