简体   繁体   中英

Call F# `printfn` from C#

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 ?

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.

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.

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