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:
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 ” (0x1) has exited with code 0 (0x0).
Done.
Waiting for debug commands…
The program ‘[8] Micro Framework application: Managed’ has exited with code 0 (0x0).
The code for this solution is located here.
Happy hacking!
One comment