Interoperability with .NET

I had a hard time now struggling with running a Julia script via include("...") from my C# GUI.
There wasn’t a problem when using Julia 0.6 but with 1.1 it failed silently.

Finally I found a solution and during my way to it I was able to get some exception string from the Julia call.
This is now my current code to call Julia 1.1 (or above) and run a Julia script from C#:

using System;

using System.Runtime.InteropServices;
using System.IO;

namespace julia
{
    class NativeMethods
    {
        
        [DllImport("kernel32.dll")]
        public static extern bool SetDllDirectory(string pathName);

        [DllImport("libjulia.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern void jl_init__threading();

        [DllImport("libjulia.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr jl_eval_string(string str);

        [DllImport("libjulia.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr jl_exception_occurred();

        [DllImport("libjulia.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr jl_typeof_str(IntPtr value);

        [DllImport("libjulia.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void jl_atexit_hook(int a);

        public static void Julia(string juliaDir, string juliaScriptDir, string projectPath)
        {
            SetDllDirectory(juliaDir);

            jl_init__threading();

            string script = @"Base.include(Base,raw""d:\Temp\test.jl"";)";
            //string script = @"include(raw""d:\Temp\test.jl"";)";
            jl_eval_string(script);
            IntPtr exception = jl_exception_occurred();
            if (exception != (IntPtr)0x0)
            {
                string exceptionString = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(jl_typeof_str(jl_exception_occurred()));
                Console.WriteLine(exceptionString);
            }

            jl_atexit_hook(0);
        }
    }
}

If you use the out-commented statement

string script = @"include(raw""d:\Temp\test.jl"";)";

the exceptionString will be "UndefVarError" and the script will not run.

The call is

julia.NativeMethods.Julia(juliaDir, juliaScriptDir, projectPath);

Parameter juliaDir must be the folder where libjulia.dll resides, e.g. c:\\Programs\\Julia-1.1.0\\bin\\.

The other two paramers (juliaScriptDir and projectPath) are not used in this example.

1 Like