Loading assemblies dynamically from an SD card with a netduino

Spiral Gears

Spiral Gears

In my previous post, I showed how to connect an SD card to a netduino to load resources from it, such as strings and bitmaps. I also wanted to be able to load assemblies dynamically. Having struggled with this last bit for a while, I wanted to document in a post how to accomplish it.

First, here’s the code of the target assembly being loaded from the SD card as a little-endian .pe file, which is critical to make everything work on the netduino. The assembly in PE format can be found under the \bin\Debug\le or \bin\Release\le directories where you compiled your solution:

Little-endian assembly location

This assembly only references Microsoft.SPOT.Native and mscorlib, both of which are already loaded in the calling assembly below. This is important because the assembly is explicitly loaded and any dependency also needs to be dynamically loaded.

Note the bold string in Print(): it will be in the output at the very end of this post.

using System;
using System.Reflection;
using Microsoft.SPOT;

namespace ASSM
{
public class TestClass
{
public void Print()
{
Debug.Print(“Hello from ” + this.ToString());
}
}
}

Now for the the loader assembly:

using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.IO;
using SecretLabs.NETMF.Hardware.Netduino;

namespace AppDomainTest
{
public class Test
{
public static void Main(string[] args)
{
StorageDevice.MountSD(“SD”, SPI.SPI_module.SPI1, Cpu.Pin.GPIO_Pin10 );

using (FileStream assmfile = new FileStream(@”SD\assm.pe”, FileMode.Open, FileAccess.Read, FileShare.None))
{
byte[] assmbytes = new byte[assmfile.Length];
assmfile.Read(assmbytes, 0, (int) assmfile.Length);
var assm = Assembly.Load(assmbytes);
var obj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(“ASSM, Version=1.0.0.0″, “ASSM.TestClass”);
var type = assm.GetType(“ASSM.TestClass”);

MethodInfo mi = type.GetMethod(“Print”);

mi.Invoke(obj, null);
}

StorageDevice.Unmount(“SD”);
}
}
}

And the output:

‘Microsoft.SPOT.Debugger.CorDebug.dll’ (Managed): Loaded ‘ASSM’
Hello from ASSM.TestClass
The thread ” (0×1) has exited with code 0 (0×0).
Done.
Waiting for debug commands…
The program ‘[8] Micro Framework application: Managed’ has exited with code 0 (0×0).

The code for this solution is located here.

Happy hacking!

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s