Search code examples
com

COM - use IEnumerable in ATL C++ project


I use in my C++ COM server a C# COM DLL that implements IEnumerable for iterating over a collection.

  1. How do I specify in my native code that I want to access IEnumerable -> GetEnumerator() method from the instance object of C# Dll ? Do I have to import some *.tlb in order to see IEnumerable interface in my C++ project ? Ienumerable interface I saw is defined by mscorelib.dll

  2. Can I further expose an IEnumerable interface to my clients (defined in IDL in my C+ project). An example would be helpful


Solution

  • It is automatically translated by the type library exporter, System.Collections.IEnumerator is [ComVisible] and gets translated to IEnumVARIANT. For example:

    using System;
    using System.Collections;
    using System.Runtime.InteropServices;
    
    [ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IExample {
        IEnumerator GetEnumerator();
    
    }
    [ComVisible(true), ClassInterface(ClassInterfaceType.None)]
    public class Example : IExample {
        public IEnumerator GetEnumerator() {
            yield return 42;
        }
    }
    

    Gets translated to this type library fragment:

    // TLib :     // TLib : mscorlib.dll : {BED7F4EA-1A96-11D2-8F08-00A0C9A6186D}
    importlib("mscorlib.tlb");
    // TLib : OLE Automation : {00020430-0000-0000-C000-000000000046}
    importlib("stdole2.tlb");
    
    // Forward declare all types defined in this typelib
    interface IExample;
    
    [
      odl,
      uuid(9B046FDE-9234-3DE7-B055-DADE8F7B4A99),
      version(1.0),
      dual,
      oleautomation,
      custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "IExample")    
    
    ]
    interface IExample : IDispatch {
        [id(0xfffffffc)]
        HRESULT GetEnumerator([out, retval] IEnumVARIANT** pRetVal);
    };
    

    Note the importlib directive for mscorlib.tlb, present in c:\windows\microsoft.net\framework\v2.0.50727 and found by the compiler without help.