.net - IronPython:使用脚本中的参数调用 C# 函数

标签 .net ironpython

我正在尝试将 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

我错过了什么吗?

注意事项:

  1. Out 参数也可以与标准库中的函数完美配合。
  2. 大多数时候,因为我使用的是外部库中的函数,所以无法更改方法签名以避免使用 out 参数。

最佳答案

将 C# 类的可见性从默认更改为公共(public)可以解决该问题。

不知道为什么...

关于.net - IronPython:使用脚本中的参数调用 C# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18786995/

相关文章:

c# - 使用数据注释的 mvc 模型中的默认值

C# 调用 Action 跨线程访问

c# - 如何为 AES 生成持久 key

c# - 更新 Active Directory 用户登录名域

python - 使用 pyc 编译 IronPython - 没有名为 numpy 的模块

.net - tableLayoutPanel 列宽

ironpython - 复制ScriptScope?

.net - 即使 EF 可以成功连接,Asp.Net Identity 也无法连接到数据库

python - 从嵌入式 python 安装中打开 REPL

.net - WPF 是 Windows 应用程序的选择吗?