繁体   English   中英

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

[英]Is there a way to pass a F# method to a Python function?

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

程序.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

你好世界.py

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

    def exec(self, printMsg):
        printMsg()

But I get Python.Runtime.PythonException: 'TypeError: object is not callable' on the helloWorld?exec(printMsg) line of Program.fs , caused by the call to printMsg() from Python.

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM