簡體   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