f#powerPack codeDom中的“CompileAssemblyFromSource”

时间:2013-08-08 22:42:17

标签: dynamic f# codedom powerpack compileassemblyfromsource

我正在尝试使用基本程序来动态编译和运行f#代码。我正在尝试运行以下代码:

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"

来自此网站:http://infsharpmajor.wordpress.com/2012/04/01/how-to-dynamically-synthesize-executable-f-code-from-text/

我遇到的问题是以下一行:

let result = provider.CompileAssemblyFromSource( options, [|codeString|] ) 

我获得例外的地方:The System cannot find the file specified.

我已经包含了必需的引用Fsharp.compiler.codeDom.dllFsharp.compiler.dll,我不确定还有什么问题。我目前正在尝试从{code}获取CodeDom的dll源代码并逐步完成它,但如果有人能够看到我忽略的一些问题,那将会让我感到很头疼。

感谢您的时间, -Alper

1 个答案:

答案 0 :(得分:3)

在F#PowerPack下面,CodeDOM实现使用F#编译器生成代码,这意味着它需要一种方法来查找编译器和相关的元数据。

首先,您可能需要将FSharp.Core.sigdata文件复制到bin文件夹(元数据)。您可能还需要将F#编译器(fsc.exe)添加到路径中,或者只是将其复制到bin文件夹中(fsc.exe位于C:\ Program Files(x86)\ Microsoft SDKs \ F#\ 3.0 \ Framework \ V4.0)。在安装了Visual Studio 2012的Windows 8计算机上,Atleast这对我有用。