0

There is a 3rd-party .Net assembly that defines an imported COM interface, gets an object from another COM object and casts it to the imported interface:

[ComImport, Guid(...), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMyInterface
{
    //...
}

void SomeMethod(object obj)
{
    IMyInterface iface = obj as IMyInterface ;
    if (iface == null)
        throw("Cannot get IMyInterface");
}

The method is public, while the imported COM interface is internal. How do I create my own managed object that implements that COM interface? The obvious solution of re-importing the same interface in my assembly does not work:

[ComImport, Guid(...), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMyInterface
{
    //...
}

class MyClass : IMyInterface
{
}

SomeMethod(new MyClass());

Despite having the same GUID and being marked as a COM interface, the .Net runtime treats the imported interfaces as 2 different interfaces and does not cast my object to the interface declared in the other assembly.

I cannot reference the imported interface from the first assembly because it's not declared as public. Can I somehow instruct the .Net runtime to create an RCW for my managed object and hide the actual one or otherwise override the default casting behavior?

I am aware of the dynamic binder, however the code needs to run on .Net 2.0+, so it is unfortunately not an option.

Ivan Shcherbakov
  • 2,063
  • 14
  • 23
  • I answered a similar question [here](http://stackoverflow.com/a/26796534/1768303). I believe that solution should work for .NET 2.0+. – noseratio Jan 27 '15 at 05:31

1 Answers1

0

If you're stuck using .NET 2.0, your best would be to use reflection to grab the type from the other assembly and then use Marshal.CreateWrapperOfType().

For example, you could call it like this:

var t1 = Type.GetType(assemblyQualifiedName);
object properlyTypedObj = System.Runtime.InteropServices.Marshal.CreateWrapperOfType(myobj, t1);
Bryce Wagner
  • 2,640
  • 1
  • 26
  • 43
  • 1
    This won't work, because both interfaces are managed ones. One approach that does work is [this](http://stackoverflow.com/a/26796534/1768303). – noseratio Jan 27 '15 at 05:34
  • I was assuming the original object is an actual native COM object, not a .NET object. I also missed the part where he was creating his own managed class to implement the interface. If it is truly native COM, the simpler solution is just re-import the COM type library and create the COM object through that... if possible. – Bryce Wagner Jan 27 '15 at 13:11