2013-08-08 54 views
5

Tôi đang cố gắng thực hiện một chương trình cơ bản để biên dịch động và chạy mã f #. Tôi cố gắng để chạy các đoạn mã sau:"CompileAssemblyFromSource" trong f # powerPack codeDom

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" 

từ trang web này: http://infsharpmajor.wordpress.com/2012/04/01/how-to-dynamically-synthesize-executable-f-code-from-text/

Vấn đề tôi đang gặp là với dòng sau:

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

Nơi tôi có được ngoại lệ: The System cannot find the file specified.

Tôi đã bao gồm các tài liệu tham khảo bắt buộc Fsharp.compiler.codeDom.dllFsharp.compiler.dll và tôi không chắc chắn vấn đề nào khác có thể xảy ra. Tôi hiện đang cố gắng để có được mã nguồn dll cho CodeDom tắt của codeplex và bước qua nó, nhưng nó sẽ giúp tôi tiết kiệm rất nhiều đau đầu nếu ai đó có thể nhìn thấy một số vấn đề tôi nhìn.

Cảm ơn bạn đã dành thời gian, -Alper

+0

Liên kết sau bao gồm mã tối thiểu để biên soạn bộ nhớ: http://stackoverflow.com/questions/15313404/in-application-script-hosting-how-does-tryfsharp-org-work –

+0

Vấn đề này có vẻ liên quan đến http: //stackoverflow.com/questions/2733415/fsharp-core-sigdata-not-found-alongside-fsharp-core –

Trả lời

3

Bên dưới thực hiện CodeDOM F # PowerPack của sử dụng F # biên dịch để tạo ra mã, có nghĩa là nó cần một cách để tìm ra trình biên dịch và siêu dữ liệu có liên quan.

Trước hết bạn có thể cần phải sao chép tệp FSharp.Core.sigdata vào thư mục bin của bạn (siêu dữ liệu). Bạn cũng có thể cần phải thêm trình biên dịch F # (fsc.exe) vào đường dẫn của bạn hoặc cách khác chỉ cần sao chép nó vào thư mục bin của bạn (fsc.exe là trong C: \ Program Files (x86) \ Microsoft SDKs \ F # \ 3.0 \ Framework \ v4.0). Atleast này làm việc cho tôi trên máy tính Windows 8 của tôi với Visual Studio 2012 được cài đặt.