Main Site Documentation

Interopt: Post an Event from Native to Managed


#1

To post an event from native to managed, TinyCLR provides RaiseEvent function, and the example below show how to use it in basic and simple way.
This topic is assuming that you already know how to implement interopt in TinyCLR.

In managed side:

using System.Runtime.CompilerServices;
using GHIElectronics.TinyCLR.Native;

namespace InteroptTest
{
    public class MyNativeClass
    {
        [MethodImpl(MethodImplOptions.InternalCall)]
        public extern void DoSomething();

        private NativeEventDispatcher dispatcher;

        public void SetupEventHandler()
        {
            if (this.dispatcher == null)
            {
                this.dispatcher = NativeEventDispatcher.GetDispatcher("InteroptTestEvent");
            }

            this.dispatcher.OnInterrupt += Dispatcher_OnInterrupt;
        }

        private void Dispatcher_OnInterrupt(string data0, long data1, long data2, long data3, System.IntPtr data4, System.DateTime timestamp)
        {
            System.Diagnostics.Debug.WriteLine("!!!From native!!! ");
            System.Diagnostics.Debug.WriteLine("data0 " + data0);
            System.Diagnostics.Debug.WriteLine("data1 " + data1);
            System.Diagnostics.Debug.WriteLine("data2 " + data2);
            System.Diagnostics.Debug.WriteLine("data3 " + data3);
            System.Diagnostics.Debug.WriteLine("data4 " + data4);
            System.Diagnostics.Debug.WriteLine("timestamp " + timestamp.Ticks);
        }
    }
}

Native code:

#include "InteroptTest.h"

TinyCLR_Result Interop_InteroptTest_InteroptTest_MyNativeClass::DoSomething___VOID(const TinyCLR_Interop_MethodData md) {

	auto interopManager = md.InteropManager;
	
	interopManager->RaiseEvent(interopManager, "InteroptTestEvent", "FromDoSomeThing", (uint64_t)12, (uint64_t)(34), 56, 78, 0);
	
    return TinyCLR_Result::Success;
}