簡體   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