如何在已编译的F#程序中执行字符串中的F#代码?

16

我该如何在一个已编译的F#程序中从字符串中执行F#代码?

3个回答

19
这是一个使用FSharp CodeDom编译字符串为程序集,并将其动态加载到脚本会话中的小脚本。它使用类型扩展来允许在参数上设置有用的默认值(希望在不久的将来,let绑定函数将支持可选、命名和params参数)。
#r "FSharp.Compiler.dll"
#r "FSharp.Compiler.CodeDom.dll"

open System
open System.IO
open System.CodeDom.Compiler
open Microsoft.FSharp.Compiler.CodeDom

let CompileFSharpString(str, assemblies, output) =
        use pro = new FSharpCodeProvider()
        let opt = CompilerParameters(assemblies, output)
        let res = pro.CompileAssemblyFromSource( opt, [|str|] )
        if res.Errors.Count = 0 then 
             Some(FileInfo(res.PathToAssembly)) 
        else None

let (++) v1 v2   = Path.Combine(v1, v2)    
let defaultAsms  = [|"System.dll"; "FSharp.Core.dll"; "FSharp.Powerpack.dll"|] 
let randomFile() = __SOURCE_DIRECTORY__ ++ Path.GetRandomFileName() + ".dll"   

type System.CodeDom.Compiler.CodeCompiler with 
    static member CompileFSharpString (str, ?assemblies, ?output) =
        let assemblies  = defaultArg assemblies defaultAsms
        let output      = defaultArg output (randomFile())
        CompileFSharpString(str, assemblies, output)     

// Our set of library functions.
let library = "

module Temp.Main
let f(x,y) = sin x + cos y
"
// Create the assembly
let fileinfo = CodeCompiler.CompileFSharpString(library)

// Import metadata into the FSharp typechecker
#r "0lb3lphm.del.dll"

let a = Temp.Main.f(0.5 * Math.PI, 0.0)     // val a : float = 2.0

// Purely reflective invocation of the function.
let asm = Reflection.Assembly.LoadFrom(fileinfo.Value.FullName)
let mth  = asm.GetType("Temp.Main").GetMethod("f")

// Wrap weakly typed function with strong typing.
let f(x,y) = mth.Invoke(null, [|box (x:float); box (y:float)|]) :?> float

let b = f (0.5 * Math.PI, 0.0)              // val b : float = 2.0

要在编译程序中使用它,您需要使用完全反射调用。

当然,与许多社区中我们紧急请求的完整脚本API相比,这只是一个玩具。

祝好运,

Danny


5

最近在这个领域取得了一些进展。现在你可以使用FSharp.Compiler.Service来进行编译。

FSharp.Compiler.Service 5.0.0是从NuGet中获取的,以下是一个简单的示例:

open Microsoft.FSharp.Compiler.SimpleSourceCodeServices
let compile (codeText:string) = 
    let scs = SimpleSourceCodeServices()
    let src,dllPath = 
        let fn = Path.GetTempFileName()
        let fn2 = Path.ChangeExtension(fn, ".fs")
        let fn3 = Path.ChangeExtension(fn, ".dll")
        fn2,fn3
    File.WriteAllText(src,codeText)
    let errors, exitCode = scs.Compile [| "fsc.exe"; "-o"; dllPath; "-a";src; "-r"; "WindowsBase"; "-r" ;"PresentationCore"; "-r"; "PresentationFramework" |]
    match errors,exitCode with
    | [| |],0 -> Some dllPath
    | _ -> 
        (errors,exitCode).Dump("Compilation failed")
        File.Delete src
        File.Delete dllPath
        None

然后,关键在于使用Assembly.LoadFrom(dllPath)将其加载到当前应用程序域中。

接着使用反射调用dll中的内容(或可能使用Activator.CreateInstance)。

LinqPad示例用法


5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接