在C#中嵌入IronPython

10

我正在研究如何在C#中使用IronPython,但似乎找不到所需的文档。基本上,我正在尝试从.py文件调用方法到C#程序。

以下是打开模块的代码:

var ipy = Python.CreateRuntime();
var test = ipy.UseFile("C:\\Users\\ktrg317\\Desktop\\Test.py");

但是,我不确定如何访问其中的方法。我看到的示例使用了动态关键字,但是,在我的工作中,我只能使用C# 3.0。

谢谢。

2个回答

9

请查看Voidspace网站上的嵌入

在那里有一个例子,IronPython计算器和求值器通过从C#程序调用的简单Python表达式求值器实现。

public string calculate(string input)
{
    try
    {
        ScriptSource source =
            engine.CreateScriptSourceFromString(input,
                SourceCodeKind.Expression);

        object result = source.Execute(scope);
        return result.ToString();
    }
    catch (Exception ex)
    {
        return "Error";
    }
}

7
您可以尝试使用以下代码:
ScriptSource script;
script = eng.CreateScriptSourceFromFile(path);
CompiledCode code = script.Compile();
ScriptScope scope = engine.CreateScope();
code.Execute(scope);

这段内容来自此文

或者,如果您喜欢调用方法,可以使用类似于以下内容的方法,

using (IronPython.Hosting.PythonEngine engine = new IronPython.Hosting.PythonEngine())
{
   engine.Execute(@"
   def foo(a, b):
   return a+b*2");

   // (1) Retrieve the function
   IronPython.Runtime.Calls.ICallable foo = (IronPython.Runtime.Calls.ICallable)engine.Evaluate("foo");

   // (2) Apply function
   object result = foo.Call(3, 25);
}

This example is from here.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接