Reputation: 6422
How can I call F# printfn
directly from C# code? I see there's a
T PrintfModule.PrintFormat<T>(PrintfFormat<T, TextWriter, Unit,Unit> format)
For example, I have F# assembly that defines x
:
type R = { r: R }
let rec x = { r = x }
In another C# assembly, how can I print x
by calling code that is equivalent to printfn "%A" x
with PrintfModule.PrintFormatLine
?
Upvotes: 0
Views: 324
Reputation: 6422
A shorter version of AlexAtNet's anwser is:
PrintfModule
.PrintFormatLine(
new PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit, Program.R>("%A"))
.Invoke(Program.x);
Although I don't understand why there's a need of casting (PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit>)
. If someone knows the reason please teach me.
Upvotes: 2
Reputation: 13522
I've created F# file Program.fs:
open System
type R = { r: R }
let rec x = { r = x }
[<EntryPoint>]
let main argv =
printfn "%A" x
0
compiled it and then decompiled to C#:
using Microsoft.FSharp.Core;
...
public static Program.R x {
get { return \u0024Program.x\u00406; }
}
[EntryPoint]
public static int main(string[] argv)
{
\u0024Program.init\u0040 = 0;
int init = \u0024Program.init\u0040;
ExtraTopLevelOperators
.PrintFormatLine<FSharpFunc<Program.R, Unit>>(
(PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit>)
new PrintfFormat<FSharpFunc<Program.R, Unit>, TextWriter, Unit, Unit, Program.R>("%A")).Invoke(Program.x);
return 0;
}
public sealed class R : IEquatable<Program.R>, IStructuralEquatable, IComparable<Program.R>, IComparable, IStructuralComparable
{
internal Program.R r\u0040;
public Program.R r { get { return this.r\u0040; } }
public R(Program.R r) { this.r\u0040 = r; }
}
Hope it will give you a hint how to do that.
Upvotes: 1