Embedding IronPython in C#

佐手、 提交于 2019-11-27 14:09:13

See embedding on the Voidspace site.

An example there, The IronPython Calculator and the Evaluator works over a simple python expression evaluator called from a C# program.

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

You can try use the following code,

ScriptSource script;
script = eng.CreateScriptSourceFromFile(path);
CompiledCode code = script.Compile();
ScriptScope scope = engine.CreateScope();
code.Execute(scope);

It's from this article.

Or, if you prefer to invoke a method you can use something like this,

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!