简体   繁体   English

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

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

I am trying to call a python function from F#.我正在尝试从 F# 调用 python function。 So far, I managed to call a simple Python function (eg: to print a string).到目前为止,我设法调用了一个简单的 Python function (例如:打印字符串)。 The problem is that I can't manage to pass a F# method to my Python function and call it from here.问题是我无法将 F# 方法传递给我的 Python function 并从这里调用它。

Program.fs程序.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你好世界.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. 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.

You need to construct a delegate from your F# function, then pass it to Python.您需要从 F# function 构造一个委托,然后将其传递给 Python。 I think System.Action(printMsg) should suffice.我认为System.Action(printMsg)就足够了。

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

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