Message Boards Message Boards

C# + System Modeler + Wolfram Language

Posted 9 years ago

Here I am going to show an example involving NETLink so that Windows users can use the System Modeler simulation through a NET/C# interface.


Code: SimpleLink.cs

using System;
using Wolfram.NETLink;

public class SimpleLink
     public static void Main (String[] args)
           // This launches the Mathematica kernel :

            IKernelLink ml = MathLinkFactory.CreateKernelLink ();

           // Discard the initial InputNamePacket the kernel will send when launched.
            ml.WaitAndDiscardAnswer ();

           // Check the version of Mathematica Kernel:
           string ver = ml.EvaluateToOutputForm ("$Version", 0);
           Console.WriteLine ("Mathematica version: " + ver);

           DateTime date1 = DateTime.Now;
           ml.Evaluate ("Get[\"test.m\"]");
           ml.WaitAndDiscardAnswer ();
           DateTime date2 = DateTime.Now;

           System.TimeSpan diff1 = date2.Subtract (date1);

           Console.WriteLine ("The Model data is loaded successfully.");
           Console.WriteLine ("Loading time: " + diff1.TotalSeconds.ToString ("F2") + " sec");
           Console.WriteLine ("Enter a real number between 0 and 2: \n Type \"exit\" to terminate.");

           double value;
           double res;

           while (true) {
                 string line = Console.ReadLine ();
                 if (line == "exit") // Check string
                   if (double.TryParse (line, out value)) {
                        ml.Evaluate ("m[\"der(pipe.T)\"][" + value + "]");
                        ml.WaitForAnswer ();
                        res = ml.GetDouble ();
                        Console.WriteLine ("-----------------------------------------------");
                        Console.WriteLine ("Time spot = " + value + " sec\n");
                        Console.WriteLine (
                              "sample function m[\"der(pipe.T)\"]["
                               + value + "] = " + res.ToString ("F3"));
                        Console.WriteLine ("-----------------------------------------------\n");
                   else {
                        Console.WriteLine ("Not a double!");

            ml.Close ();
           Console.WriteLine ("Wolfram Kernel is termiated!");
           Console.WriteLine ("Press any key to close the terminal ... ");
           Console.ReadKey ();

What I am doing here is to launch Wolfram kernel first and load a file called test.m or test2.m. test.m simply loads the WSMLink and the built-in model Modelica.Thermal.FluidHeatFlow.Examples.PumpAndValve. test2.m does the same thing except it loads a pre-compiled .sme file to save some loading time. I have attached these two files with this article. The test.m, test2.m and PipeAndValve.m file should be put in the $HomeDirectory for your convenience because I did not specify where to load them in the code. Wolfram kernel will look for these files in the $HomeDirectory automatically.

This link explains the "IKernelLink", "CreateKernelLink" and "EvaluateToOutputForm"/"Evaluate". I skip these here to leave for your study pace.

If you run the model in System Modeler, you can find many output options. I picked one of them: der(pipe.T). Take a look at the screenshot below. On the right side, you should be familiar with how to extract the numerical result of our simulation at a given time. The terminal on the left side also gets the same result.


I use the following NETLink API to pass the value in the Wolfram Kernel to the NET/C# executive,

ml.Evaluate ("m[\"der(pipe.T)\"][" + value + "]"); // value = time spot s.t. t = 0.1 ,0.2 ...
ml.WaitForAnswer (); // wait for the kernel's return packet
res = ml.GetDouble (); // pass the numerical value to NET as a native type

Note that I included some escape sign to keep the string "der(...)" inside the command string after "ml.Evaluate". Compare the results from the terminal with that in Mathematica and the plot in System Modeler, I am assured that the C# program works correctly.


How to Compile the code:

  • Use VS 2013 command line interface: Just cd/chdir to the place where you save the code within the VS 2013 command line tool. Make sure that you also have these three file included at the same location: "ml32i4.dll", "ml64.dll", "Wolfram.NETLink.dll". If you installed Mathematica at the default location, you can find them at

    C:\Program Files\Wolfram Research\Mathematica\10.1\SystemFiles\Links\NETLink

After you move them to the same directory as that of the source code, run the code below

csc /target:exe /reference:Wolfram.NETLink.dll filename.cs
  • Use VS 2013 GUI: Follow the instruction in VS to create a new C# console application. You need to paste the sample code to the .cs source file in the project. Then move the "Wolfram.NETLink.dll" to the project/solution folder. In the Solution Explorer, right click Reference and browse to the project file and add the Wolfram.NETLink.dll


Now you can build the solution. By default the process will create a bin/Debug folder. Put the "ml32i4.dll" and "ml64i4.dll" there. Then you can compile the code in debug mode by clicking the start button.


POSTED BY: Shenghui Yang
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract