有没有办法将 F# 方法传递给 Python 函数?

时间:2021-05-10 07:30:36

标签: python c# .net f# python.net

我正在尝试从 F# 调用 python 函数。到目前为止,我设法调用了一个简单的 Python 函数(例如:打印一个字符串)。问题是我无法将 F# 方法传递给我的 Python 函数并从这里调用它。

程序.fs

let printMsg () = Console.WriteLine "Print from F#"

[<EntryPoint>]
let main argv =
    Environment.SetEnvironmentVariable ("PATH", pythonPath + Environment.GetEnvironmentVariable "PATH")
    PythonEngine.Initialize ()

    let import = PythonEngine.ImportModule "HelloWorld"
    let helloWorld = import?HelloWorld()

    helloWorld?exec(printMsg)

    PythonEngine.Shutdown ()

    0

Helloworld.py

class HelloWorld:
    def __init__(self):
        print("__init__")

    def exec(self, printMsg):
        printMsg()

但是我在 Python.Runtime.PythonException: 'TypeError : object is not callable'helloWorld?exec(printMsg) 行得到 Program.fs,这是由 Python 调用 printMsg() 引起的。

1 个答案:

答案 0 :(得分:3)

您需要从 F# 函数构造一个委托,然后将其传递给 Python。我认为 System.Action(printMsg) 应该足够了。

相关问题