Created
February 5, 2018 18:40
-
-
Save ninjarobot/66e578910fe3191bc6f71f36d944384b to your computer and use it in GitHub Desktop.
Example reading data from a dynamically compiled module.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Works from .NET Core (netcoreapp2.0), just add nuget package FSharp.Compiler.Service | |
open System | |
open System.IO | |
open Microsoft.FSharp.Compiler.SourceCodeServices | |
let nugetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".nuget") | |
let systemRuntimePath = Path.Combine(nugetPath, "packages/System.Runtime/4.3.0/ref/netstandard1.5/System.Runtime.dll") | |
[<EntryPoint>] | |
let main argv = | |
async { | |
let sourceTok = FSharpSourceTokenizer ([], Some "/tmp/blah.fsx") | |
let tokenizer = sourceTok.CreateLineTokenizer | |
let checker = FSharpChecker.Create () | |
let tempPath = Path.GetTempFileName() | |
let tempSourcePath = Path.ChangeExtension(tempPath, ".fsx") | |
let tempOutPath = Path.ChangeExtension(tempPath, ".dll") | |
File.WriteAllText (tempSourcePath, """ | |
module M | |
let serverPort = 2220 | |
""") | |
printfn "Building %s" tempOutPath | |
let! errors, exitCode = checker.Compile ([|"fsc.exe"; "-o"; tempOutPath; "-a"; tempSourcePath; "--targetprofile:netcore"; "--simpleresolution"; "--noframework"; "-r:" + systemRuntimePath|]) | |
printfn "%A" (errors, exitCode) | |
let a = System.Reflection.Assembly.LoadFrom(tempOutPath) | |
let modl = a.GetTypes() |> Array.find (fun t -> t.Name = "M") | |
let serverPortProp = modl.GetProperty ("serverPort") | |
serverPortProp.GetValue(null) | |
|> printfn "value of M.serverPort is: %A" | |
File.Delete (tempOutPath) | |
File.Delete (tempSourcePath) | |
} |> Async.RunSynchronously | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment