从 Haxe 内部调用外部 Python class 函数

Call external Python class function from inside Haxe

假设我在 Python 中有以下 class:

class TestPy:
    def __init__(self):
        pass
    def f(self):
        return("Hello World")

我想从 Haxe 中调用函数 TestPy.f。然后我可以通过指定一个 extern class via

来告诉编译器这个函数
extern class TestPy { 
    public function new():Void;
    public function f():String;
}

然后使用这个声明来调用这个函数

class Test {
    public static function main():Void {
        var py:TestPy = new TestPy();
        trace(py.f());
    }
}

这可以编译,但是生成的代码如下所示:

# Generated by Haxe 3.4.7
# coding: utf-8
class Text:
    __slots__ = ()
    @staticmethod
    def main():
        py = TestPy()
        print(str(py.f()))
Text.main()

这不起作用,因为带有 TestPy class 的模块从未在代码中导入:

NameError: name 'TestPy' is not defined

所以我的问题是如何建议 Haxe 在生成的代码中添加导入语句(例如 from testmodule import TestPy)?

只需将 @:pythonImport 元数据添加到您的外部文件。 所以,像这样:

@:pythonImport('testmodule', 'TestPy')
extern class TestPy {...

免责声明:尚未对此进行测试,因此这可能不是完全正确的答案,但元数据是 documented in the manual