Search code examples
c#windowscomclr

How does COM work?


I have a dll that is allegedly a COM object. I'm trying to understand how exactly is the CLR able to figure out which function to call when no export function is available in the dll (I checked using depends).

  [Guid("DEADBEEF....")]
  [TypeLibType(...)]
  [ComImport]
  public interface ISomething
  {
    [DispId(1)]
    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    [return: MarshalAs(UnmanagedType.IDispatch)]
    object DoSomething([MarshalAs(UnmanagedType.IDispatch), In] object something);

}

In here and I checked the MSIL there is no information about what address or function name, or offset it is located at.

Furthermore, there seems to be no information about how an object is layed out so its vtable pointer is passed, etc.

What magic is this?


Solution

  • From (unmanaged) code, one would use LoadTypeLib/LoadTypeLibEx on the "type library" file associated with the COM object. Quite commonly, that's the EXE or DLL registered for the COM object itself (but it could also be a standalone TLB file, a foreign type library etc). The documentation for LoadTypeLib has further pointers at https://msdn.microsoft.com/en-us/library/windows/desktop/ms221027(v=vs.85).aspx.

    Once the ITypeLib/ITypeLib2 type library interface is obtained, it provides all the COM object info, including interfaces, vtable layout, prototypes etc. Full documentation is at https://msdn.microsoft.com/en-us/library/windows/desktop/ms221549(v=vs.85).aspx.

    An example of LoadTypeLib in action is the OLE/COM Object Viewer provided with most versions of Visual Studio, which can essentially decompile a given type library back to an IDL. I can't post more than 2 URLs, but lookup https-//msdn.microsoft.com/en-us/library/d0kh9f4c.aspx.

    In managed code, the compiler does the importing of the type library transparently, though behind the scenes it's doing basically the same work as the OLE/COM Viewer, plus adding the necessary managed wrappers. See https-//msdn.microsoft.com/en-us/library/xwzy44e4(v=vs.110).aspx for more details.