Posting native events in nanoFramework

To deal with situations that require native coding or when one faces the situation of needing to add native code that has no place on the core library, there is Interop. It’s a rather powerful feature that opens immense possibilities.

Sending data from the native code to the C# managed application can be done easily by using either parameters passed by reference or sending the data on the return value. But… what if you need to signal your application of random events that occurs on the native code? Well now you can!

Support for CustomEvent has just been added to nanoFramework.Runtime.Events.

Let me explain how easy it is to use this cool feature. 😉

On your native code, all you have to do it’s just adding a simple line of code. Really! Like this:

PostManagedEvent( EVENT_CUSTOM, 0, 1111, 2222 );

The payload that’s available consists of the last two parameters on that call. The first it’s an uint16 and the second an uint32.

Feel free to use those as you please. This includes all possible variants like: use only the first one, or the second or none if you just need to signal something. Or, if you have a lot of events to process, you can encode those.

This is it. Now up to the managed application!

Requirements? Add a reference to nanoFramework.Runtime.Events NuGet.

using nanoFramework.Runtime.Events;

Last step is setting up the event handler:

CustomEvent.CustomEventPosted += CustomEventHandler;

The event handler receives the data payload posted on the native code.

private static void CustomEventHandler(object sender, CustomEventArgs e)
    Console.WriteLine($"Custom event received. Data1: { e.Data1 } Data2: { e.Data2 }.");

And this is it! Easy-peasy.

When the event handler is called you can access the data posted on the native code through the properties in CustomEventArgs class.

If you need, grab the sample from the official repo here.

Now, to paraphrase Carl Franklin from the .NET Rocks podcast: “go write some code!” 😊

One thought on “Posting native events in nanoFramework

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s