2014-06-18 17 views
5

C# 'dan IronPython işlevini arıyorum. Tanıma göre, bu işlev orijinal kapsamını yakalar. Daha sonra bunu açık bir kapsam olmadan çağırdığımda, yine de o orijinal kapsamdaki değerlere erişebilir. Kapsam değerlerini değiştirsem bile, yeni değerleri doğru okur. Bu örnekte bir göz atın: IronPython işlevini çağırırken CodeContext'in anlamı

using IronPython.Hosting; 
using IronPython.Runtime; 
using IronPython.Runtime.Operations; 
using Microsoft.Scripting; 
using Microsoft.Scripting.Hosting; 

namespace IronPythonFuncTest { 
    class Program { 
     static void Main() { 
      ScriptEngine scriptEngine = Python.CreateEngine(); 

      // Create scope with a global value for the script to use 
      ScriptScope scriptScope = scriptEngine.CreateScope(); 
      scriptScope.SetVariable("someGlobalValue", 10); 

      // Execute script defining function foo(x) 
      string script = "def foo(): print(someGlobalValue)"; 
      ScriptSource scriptSource = scriptEngine. 
       CreateScriptSourceFromString(script, SourceCodeKind.Statements); 
      scriptSource.Execute(scriptScope); 

      // Extract foo from the scope 
      PythonFunction foo = scriptScope.GetVariable<PythonFunction>("foo"); 

      // Change someGlobalValue 
      scriptScope.SetVariable("someGlobalValue", 42); 

      // Call foo. This prints 42, not 10 (or nothing). 
      PythonCalls.Call(foo); 
     } 
    } 
} 

Şimdi merak ediyorum: PythonCalls.Call() çoğu aşırı yükler (eğer doğru anlamak, çoğunlukla bir kapsamını temsil eder) bir CodeContext nesneyi bekliyoruz. Kod bağlamı geçmeden, yukarıdaki gibi bir IronPython işlevi çağırırsam bir şey kaybediyor muyum? Görünüşte, işlevin yaratılıştaki orijinal kapsamını yakaladığı göz önüne alındığında, ek kod içeriğinin aktarılmasında herhangi bir nokta görülmemektedir. Yapsam da fark yarattığı durumlar var mı?

cevap

0

PythonCall.Call üzerinden neden foo diyorsunuz? Bu şekilde yapmayı deneyin: Ironpython'dan scriptScope.Host.ScriptEngine.Operations.InvokeMember(CLASS-Instance, METHOD-Name, ARGUMENTS);, kendi başına CodeContext'u doğru şekilde işleyecektir. Burada örnek bir uygulama bulabilirsiniz: DlrClass/InvokeMember.

olarak bildiğim kadarıyla, CodeContext sadece kapsamı daha fazladır, sadece tanım bakmak:

/// <summary> 
/// Captures and flows the state of executing code from the generated 
/// Python code into the IronPython runtime. 
/// </summary>  
[DebuggerTypeProxy(typeof(CodeContext.DebugProxy)), DebuggerDisplay("module: {ModuleName}", Type="module")] 
public sealed class CodeContext { // ... } 

Umut bu yardımcı olur!