IronPython 2.7.4公开应用程序对象模型
本文关键字:应用程序 对象模型 IronPython | 更新日期: 2023-09-27 18:24:54
我正在尝试从IronPython文档中运行基本的托管"Exposing Application Object Model"C#示例。范围SetVariable(…)似乎不足以公开方法。对象已公开,但无法访问其方法。以下适用于旧的IronPython 1。
using System;
using IronPython.Hosting;
public class CallingDotNet {
private static void Main(string[] args) {
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("my_object_model", new CallingDotNet());
engine.CreateScriptSourceFromString("my_object_model.Foo(42)").Execute(scope);
}
public void Foo(int arg) {
Console.WriteLine("You gave me a {0}", arg);
}
}
获得以下异常wwith IronPython 2.7:
'CallingDotNet' object has no attribute 'Foo'
at IronPython.Runtime.Binding.PythonGetMemberBinder.FastErrorGet`1.GetError(CallSite site, TSelfType target, CodeContext context)
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at Microsoft.Scripting.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
at IronPython.Compiler.PythonScriptCode.Run(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
at Microsoft.Scripting.SourceUnit.Execute(Scope scope)
那么,我应该如何使用IronPython 2.7公开对象呢?
编辑:事实上,我正在尝试运行以下代码,我想我对名称空间/导入感到困惑:
using System;
using IronPython.Hosting;
namespace IronTestHosting
{
class Program
{
public class CallingDotNet
{
public static void Run(string[] args)
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("my_object_model", new CallingDotNet());
engine.CreateScriptSourceFromString("my_object_model.Foo(42)").Execute(scope);
}
public void Foo(int arg)
{
Console.WriteLine("You gave me a {0}", arg);
}
}
static void Main(string[] args)
{
CallingDotNet.Run(args);
Console.ReadLine();
}
}
}
您需要将Program
和内部类公开。由于我不完全确定的原因,所有包含的类都必须是公共的,否则IronPython将无法与您的类交互。