Search code examples
c#c++.netcomunmanaged

C# component events?


I am attempting to write a C# component which will expose events. The component is to be imported by an unmanaged C++ application. According to a few tutorials I have come up with this code (for the C# side):

namespace COMTest
{
[ComVisible(true),
Guid("02271CDF-BDB9-4cfe-B65B-2FA58FF1F64B"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITestEvents
{
    void OnTest();
}

[ComVisible(true),
Guid("87BA4D3A-868E-4233-A324-30035154F8A4")]
public interface ITest
{
    void RaiseTest();
} // End of ITest

[ComVisible(true),
Guid("410CD174-8933-4f8c-A799-8EE82AF4A9F2"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(ITestEvents))]
public class TestImplimentation : ITest
{
    public TestImplimentation()
    {
    }

    public void RaiseTest()
    {
        if (null != OnTest)
            OnTest();
    }

    public delegate void Test (); //No need to expose this delegate
    public event Test OnTest;
}
}

Now my c++ code has a simple:

#import "COMTest.tlb" named_guids raw_interfaces_only

Which generates a tlh file. This tlh file contains everything but my event (OnTest). What am I doing incorrectly?


Solution

  • COM Event Sinks are pretty evil to the uninitiated.

    The steps basically are

    • create an outgoing (source) interface
    • Implement an IConnectionPointContainer and IConnectionPoint Interfaces, use these to pass a client implementation of the source Interface

    The good news is that in the interop namespace there are attributes to help you do this (mostly) automatically (ComSourceInterfacesAttribute) There is a decent example of its usage here.