我正在尝试将 IronPython 用作 C# 应用程序中的脚本语言。脚本必须使用主应用程序提供的功能(在应用程序或外部库中实现)。
虽然这对于只有输入参数的“简单”函数非常完美(就像在我发现的任何其他示例中一样),但对于没有参数的函数会失败。
示例(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 参数。
最佳答案
将 C# 类的可见性从默认更改为公共(public)可以解决该问题。
不知道为什么...
关于.net - IronPython:使用脚本中的参数调用 C# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18786995/