← Back to articles

.Net CLR Runtime

Can LSL bytecode map onto .NET CLR? Yes — and here is the biggest Hello World I have ever written, generated at run-time with ILGenerator and OpCodes.

Tedd

The first thing I did was to see if .Net CLR looked anything like LSL ByteCode at all. As expected it did. It should be possible to convert between the two. But because we need to have scripts cross sims, the standard way of doing things might not suffice.

So, next question. How does one create CLR? Well, there are many ways. The ones I looked at as potential candidates was 1) creating an CLR code file and compiling and 2) creating CLR code run-time. I chose to go with the latter one.

Here is the important part of my sample Hello World! run-time generated CLR program. The biggest Hello World! program I’ve ever made.

private void GenerateIL(ILGenerator il, OpenSimAPI.SimWorldAPI WorldAPI)
{
/*
 * TRY
 */
il.BeginExceptionBlock();
// Push "Hello World!" string to stack
il.Emit(OpCodes.Ldstr, "Hello World!");
Push Console.WriteLine command to stack ... Console.WriteLine("Hello World!");
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));

il.ThrowException(typeof(NotSupportedException));

/*
 * CATCH
 */
il.BeginCatchBlock(typeof(Exception));
// Push "Hello World!" string to stack
il.Emit(OpCodes.Ldstr, "Something went wrong: ");
//call void [mscorlib]System.Console::WriteLine(string)
il.Emit(OpCodes.Call, typeof(Console).GetMethod("Write", new Type[] { typeof(string) }));
//callvirt instance string [mscorlib]System.Exception::get_Message()
il.Emit(OpCodes.Callvirt, typeof(Exception).GetMethod("get_Message"));
//call void [mscorlib]System.Console::WriteLine(string)
il.Emit(OpCodes.Call,
typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
/*
 * END TRY
 */
il.EndExceptionBlock();

// Push "Return from current method, with return value if present" to stack
il.Emit(OpCodes.Ret);

} 

Written by Tedd · Oslo, Norway

Updated 5 Jan 2017

Follow the journal via RSS