Calling Clojure from .NET

后端 未结 2 578
無奈伤痛
無奈伤痛 2021-01-31 10:39

I have been spending some time playing with Clojure-CLR. My REPL is working, I can call .NET classes from Clojure, but I have not been able to figure out calling compiled Clojur

2条回答
  •  不要未来只要你来
    2021-01-31 11:03

    I'd argue you should take another tack on this. All that gen-class stuff only exists in clojure as a hack to tell the compiler how to generate wrapper Java/C# classes around the native clojure reflective-dynamic variables.

    I think it's better do all the "class" stuff in C# and keep your clojure code more native. Your choice. But if you want to go this way, write a wrapper like this:

    using System;
    using clojure.lang;
    
    namespace ConsoleApplication {
        static class Hello {
            public static int Output(int a, int b) {
                RT.load("hello");
                var output = RT.var("code.clojure.example.hello", "output");
                return Convert.ToInt32(output.invoke(a, b));
            }
        }
    }
    

    That way your C# can look like normal C#

    using System;
    
    namespace ConsoleApplication {
        class Program {
            static void Main() {
                Console.WriteLine("3+12=" + Hello.Output(3, 12));
                Console.ReadLine();
            }
        }
    }
    

    And the clojure can look like normal clojure:

    (ns code.clojure.example.hello)
    
    (defn output [a b]
      (+ a b))
    

    This will work whether you compile it or just leave it as a script. (RT.load("hello") will load the script hello.clj if it exists, or otherwise it'll load the hello.clj.dll assembly).

    This allows your clojure to look like clojure and your C# to look like C#. Plus it eliminates the static method clojure interop compiler bug (and any other interop bugs that may exist), since you're completely circumventing the clojure interop compiler.

提交回复
热议问题