I am trying to get going a basic program to dynamically compile and run f# code. I am trying to run the following code:
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"
from this site: http://infsharpmajor.wordpress.com/2012/04/01/how-to-dynamically-synthesize-executable-f-code-from-text/
The issue I am having is with the following line:
let result = provider.CompileAssemblyFromSource( options, [|codeString|] )
Where I get the exception: The System cannot find the file specified.
I have included the required references Fsharp.compiler.codeDom.dll
and Fsharp.compiler.dll
and I am not sure what else could be there issue. I am currently trying to get the dll source code for CodeDom
off of codeplex and step through it but it would save me a lot of headache if somebody is able to see some issue I am overlooking.
Thank you for your time, -Alper
Underneath the F# PowerPack's CodeDOM implementation uses the F# compiler to generate code, which means it needs a way to find the compiler and related metadata.
First off you may need to copy the FSharp.Core.sigdata file to your bin folder (the metadata). You may also need to add the F# compiler (fsc.exe) to your path or alternatively just copy it into your bin folder (fsc.exe is in C:\Program Files (x86)\Microsoft SDKs\F#\3.0\Framework\v4.0). Atleast this worked for me on my Windows 8 machine with Visual Studio 2012 installed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With