C# .Net Native AoT - How to get pointer to Managed class to pass as parameter to Com Object

Gueztt 1 Reputation point
2025-07-23T07:07:44.94+00:00

I have implemented INetworkListManagerEvents interface to get network connectivity state changes as a C# class.

In my project, the INetworkListManagerEvents is code generated via CsWin32 source generator.

Now at some point I have to use IConnectionPoint::Advise for it to work as intended.

How can I pass the instance of my C# class implementing INetworkListManagerEvents to IConnectionPoint::Advise as IUnknown*.

I can't use Marshal class so to make it trim friendly and have Native AoT compatibility.

Edit 1:

Above scenario is just for an example. There are other scenarios where event sinks needs to be implemented in c#, to get notified about, where c# managed class needs to be passed as pointer to the relevant Advise(...) function for it to work.

Windows development | Windows API - Win32
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 90,956 Reputation points
    2025-07-23T12:02:53.8033333+00:00

    You can call Advise inside the class and use this.

    This test works for on my Windows 10 22H2 OS :

    public partial class NetworkListManagerEventsClass : INetworkListManagerEvents
    {
        private INetworkListManager nlm;
        private IConnectionPoint cp;
        private int nCookie = 0;
    
        public NetworkListManagerEventsClass()
        {
            nlm = new NetworkListManager();
            IConnectionPointContainer cpc = (IConnectionPointContainer)nlm;
            if (cpc != null)
            {
                Guid guid = typeof(INetworkListManagerEvents).GUID;
                cpc.FindConnectionPoint(ref guid, out cp);
                cp.Advise(this, out nCookie);
            }
        }
    
        ~NetworkListManagerEventsClass()
        {
            cp.Unadvise(nCookie);
        }
    
        void INetworkListManagerEvents.ConnectivityChanged(NLM_CONNECTIVITY newConnectivity)
        {
            if ((newConnectivity & NLM_CONNECTIVITY.NLM_CONNECTIVITY_DISCONNECTED) != 0)
            {
                System.Diagnostics.Debug.WriteLine("Disconnected");
            }
            if ((newConnectivity & NLM_CONNECTIVITY.NLM_CONNECTIVITY_IPV4_LOCALNETWORK) != 0  ||
                (newConnectivity & NLM_CONNECTIVITY.NLM_CONNECTIVITY_IPV6_LOCALNETWORK) != 0)
            {
                System.Diagnostics.Debug.WriteLine("Local Network");
            }
            if ((newConnectivity & NLM_CONNECTIVITY.NLM_CONNECTIVITY_IPV4_INTERNET) != 0 ||
                (newConnectivity & NLM_CONNECTIVITY.NLM_CONNECTIVITY_IPV6_INTERNET) != 0)
            {
                System.Diagnostics.Debug.WriteLine("Internet");
            }
        }
    }
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.