简体   繁体   中英

Executing F# Source from C#

I'd like to find a working example of using C# to CompileAssemblyFromSource of F# code. In my current attempts, I'm unable to create the compiler, getting an exception of "NotSupportedException", message of "Compilation not supported." My guess is I'm just doing it wrong, since F# Interactive works and has to be doing something similar, but correctly.

// C#
var source = "let add x y = x + y";
var cleanProvider = new FSharp.Compiler.CodeDom.FSharpCleanCodeProvider();
var compilerParams = new System.CodeDom.Compiler.CompilerParameters();
const string outfile = "C:\\temp\\FSFoo.EXE";
compilerParams.OutputAssembly = outfile;
compilerParams.GenerateExecutable = true;

var compiler = cleanProvider.CreateCompiler();
var compilerResults = compiler.CompileAssemblyFromSource(compilerParams, source);
var results = cleanProvider.CompileAssemblyFromSource(compilerParams, source);

this code alone will compile what you want, there is extra diagnostic/debug code left in.

using FSharp.Compiler.CodeDom;
using System.CodeDom;
var codeString = "let add x y = x + y";
var provider = new FSharp.Compiler.CodeDom.FSharpCodeProvider();
Environment.CurrentDirectory.Dump("exe is going here"); // diagnostic helper
var targetFile = "FSFoo.exe";
provider .CompileAssemblyFromSource( new System.CodeDom.Compiler.CompilerParameters(){ OutputAssembly= targetFile, GenerateExecutable=true }, new []{codeString}).Dump(); // .Dump is just for diagnostics, remove if you aren't running this in linqpad
if(!System.IO.File.Exists(targetFile)){
    throw new FileNotFoundException("Could not find compiled exe",targetFile);
}

System.IO.Directory.GetFiles(Environment.CurrentDirectory,"FSFoo.exe").Dump();// .Dump is just for diagnostics, remove if you aren't running this in linqpad

other resources that may help:

http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm

"CompileAssemblyFromSource" in f# powerPack codeDom

http://tiku.io/questions/638972/run-f-code-on-server-even-when-f-is-not-installed-there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM