Yesterday, I figured out how to call some C# code from Scala. It is a small leap to then call Scala from C#. The process just gets turned around: instead of creating a C# class library and referencing it from Scala, you create a dll from Scala code and reference it in .Net.
First, I built a class in Scala similar to my C# class from yesterday:
class ScalaSpeaker {
def Speak() {
println("Hello");
}
def Speak(name: String) {
println("Hi, " + name + ", glad you could join us!")
}
}
Just like before, the Scala needs to be compiled to MSIL. There are fewer arguments needed because the Scala is not referencing any other dlls and does not contain the entry point for the executable:
<Scala.Net directory>\bin\scalacompiler.exe
–target:msil
–Xassem-extdirs <Scala.Net directory>\bin
<scala files>
Where:
- <Scala.Net directory> is the directory where the Scala.Net SVN repository was checked out to
After the MSIL has been generated, it can be turned into a dll:
ilasm /DLL <MSIL file>
Notice the /DLL flag for ilasm, this is where the magic happens.
After running ilasm, the new Scala dll can be referenced in a .Net application. I created a console application and added a reference to the dll. For the application to run propertly there are a few more dlls that need to be referenced, all of which can be found in the bin directory of the SVN repository:
CSharpFilesForBootstrap.dll
IKVM.OpenJDK.Core.dll
jfisl.dll
scalalib.dll
scalaruntime.dll
The C# is very straight forward, and surprisingly doesn’t require any extra using statements:
using System;
namespace CallScala
{
class Program
{
static void Main(string[] args)
{
var speaker = new ScalaSpeaker();
speaker.Speak();
speaker.Speak("Jim");
}
}
}

3 Responses to Calling Scala from C#