Il desiderato può essere raggiunto utilizzando F# CodeDom provider. Uno snippet eseguibile minimo di seguito mostra i passaggi richiesti. Prende un codice F # arbitrariamente presumibilmente corretto da una stringa e tenta di compilarlo in un file assembly. Se ha successo, carica questo assembly appena sintetizzato dal file dll
e invoca una funzione conosciuta da lì, altrimenti mostra qual è il problema con la compilazione del codice.
open System
open System.CodeDom.Compiler
open Microsoft.FSharp.Compiler.CodeDom
// Our (very simple) code string consisting of just one function: unit -> string
let codeString =
"module Synthetic.Code\n let syntheticFunction() = \"I've been compiled on the fly!\""
// Assembly path to keep compiled code
let synthAssemblyPath = "synthetic.dll"
let CompileFSharpCode(codeString, synthAssemblyPath) =
use provider = new FSharpCodeProvider()
let options = CompilerParameters([||], synthAssemblyPath)
let result = provider.CompileAssemblyFromSource(options, [|codeString|])
// If we missed anything, let compiler show us what's the problem
if result.Errors.Count <> 0 then
for i = 0 to result.Errors.Count - 1 do
printfn "%A" (result.Errors.Item(i).ErrorText)
result.Errors.Count = 0
if CompileFSharpCode(codeString, synthAssemblyPath) then
let synthAssembly = Reflection.Assembly.LoadFrom(synthAssemblyPath)
let synthMethod = synthAssembly.GetType("Synthetic.Code").GetMethod("syntheticFunction")
printfn "Success: %A" (synthMethod.Invoke(null, null))
else
failwith "Compilation failed"
Essere sparato-up che produce l'uscita prevista
Success: "I've been compiled on the fly!"
Se hai intenzione di giocare con lo snippet richiede riferimento FSharp.Compiler.dll
e FSharp.Compiler.CodeDom.dll
. Godere!
fonte
2012-04-01 20:09:18
Potrebbe valere la pena dare un'occhiata a questa [domanda] (http://stackoverflow.com/questions/372043/how-can-evaluate-an-expression-stored-as-a-string-in-f) –
You potrebbe anche usare [codifica f #] (http://stackoverflow.com/questions/2608114/f-equivalent-to-eval) –