繁体   English   中英

在C#中嵌入IronPython

[英]Embedding IronPython in C#

我只是在研究使用IronPython和C#,似乎无法找到任何我需要的文档。 基本上我试图将.py文件中的方法调用到C#程序中。

我有以下打开模块:

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

但是,我不确定如何访问其中的方法。 我见过的例子使用了dynamic关键字,但是,在工作中我只使用C#3.0。

谢谢。

请参阅Voidspace网站上的嵌入

这里有一个例子, IronPython Calculator和Evaluator工作在一个简单的python表达式求值程序中,该求值程序来自C#程序。

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";
    }
}

您可以尝试使用以下代码,

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);
}

这个例子来自这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM