我正在尝试在 C# 应用程序中使用 IronPython 作为脚本语言。脚本必须使用主应用程序提供的功能(在应用程序或外部库中实现)。
虽然这对于只有输入参数的“简单”函数非常有效(就像我发现的任何其他示例一样),但对于没有参数的函数,这会失败。
示例(C# 代码):
public delegate int getValue_delegate(out float value);
public int getValue(out float value)
{
value = 3.14F;
return 42;
}
public void run(string script, string func)
{
ScriptRuntime runtime = ScriptRuntime.CreateFromConfiguration();
ScriptEngine engine = runtime.GetEngine("Python");
ScriptScope scope = engine.CreateScope();
scope.SetVariable("myGetTemp", new getValue_delegate(getValue));
engine.ExecuteFile(script, scope);
}
然后是 IronPython 脚本。我希望该值应设置为 3.14,但只能设法获得 0.0。
import clr
import System
ret,value = getValue()
print("getValue -> %d => %s" % (ret, value)) # => output "getValue -> 42 => 0.0
value = clr.Reference[System.Single]()
ret = getValue(value)
print("getValue -> %d => %s" % (ret, value)) # => output "getValue -> 42 => 0.0
我错过了什么吗?
笔记:
- Out 参数也可以与标准库中的函数完美配合。
- 大多数时候,当我使用来自外部库的函数时,不可能更改方法签名以避免使用 out 参数。