到目前为止,我有一个简单的类,它包装了一个python引擎(IronPython)供我使用。虽然代码看起来很大,但其实很简单,所以我将其复制到这里,以便更清楚地说明我的问题。
代码如下:
public class PythonInstance
{
ScriptEngine engine;
ScriptScope scope;
ScriptSource source;
public PythonInstance()
{
engine = Python.CreateEngine();
scope = engine.CreateScope();
}
public void LoadCode(string code)
{
source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements);
source.Compile();
}
public void SetVariable(string key, dynamic variable)
{
scope.SetVariable(key, variable);
}
public void RunCode()
{
source.Execute(scope);
}
public void CallFunction(string function)
{
//?????? no idea what to call here
}
}
所以,它工作得很好,但它只允许我一次执行所有的python脚本。。。但我想做的是能够从pythos脚本中调用特定的函数。
那么,我的问题是:如何调用加载脚本中的特定函数?
我试图找到一些信息或教程,但不幸的是找不到任何东西。
可以使用ScriptScope.GetVariable获取实际的函数,然后像调用c#函数一样调用它。 像这样使用: C#代码:
Python代码:
我花了一段时间才弄明白,很简单。。可惜没有好的IronPython文档。希望这有帮助:)
多亏了评论中的建议,我才知道如何使用它。我现在有:
要测试它:
相关问题 更多 >
编程相关推荐