5
votes

Let's say I have a well-known interface IWellKnownInterface, which is known to be COM-visible and registered.

I also have a managed (C#, to be exact) implementation of this object:

public class MyWellKnownClass : IWellKnownInterface { ... }

And, finally, I have an extern method, which accepts the object of this interface:

[Whatever]
private static extern void ExternMethod(IWellKnownInterface veryWellKnown);

Question 1:

I would like to know what happens beneath the following code from the CLR point of view:

IWellKnownInterface a = new MyWellKnownClass();
ExternMethod(a);

I'm aware that if we're talking about calling unmanaged COM object from managed code, it's all about constructing an appropriate Runtime Callable Wrapper and delegating the calls via it with appropriate argument conversion. However, I could not find any information about the situation when we've got a managed COM object and it's being used in unmanaged code.

Question 2:

How does the dynamic type affect the behavior of the CLR in the same situation? Would it somehow change the internal managed-to-unmanaged interop logic? Maybe add some additional wrappers for the MyWellKnownClass instance?

dynamic a = new MyWellKnownClass();
ExternMethod(a);
1

1 Answers

3
votes

Question 1:

The first line does nothing but create an object. There is nothing special or different that is happening from any other CLR object. This is because nothing has been actually marshaled to unmanaged code.

However, on the second line, a COM callable wrapper is created and marshaled across to unmanaged code. Think of this as the reverse of the runtime callable wrapper, handling the calls from unmanaged code back to your managed implementation of a COM interface.

Question 2:

The dynamic type doesn't impact the call at all. In this particular case, you're passing the managed reference to unmanaged code. The type of a is MyWellKnownClass, the only thing that dynamic does is change how calls to that are resolved in managed code. When the COM callable wrapper is created, it has a hard reference to the instance of MyWellKnownClass, not to the dynamic variable; the only thing that changes is that when ExternMethod is called, the resolution of the method that is called occurs at runtime and not at compile-time.