【发布时间】:2014-09-29 22:26:29
【问题描述】:
我正在尝试运行 IronPython 文档中的基本托管“公开应用程序对象模型”C# 示例。 scope.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);
}
}
使用 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();
}
}
}
【问题讨论】:
-
您的代码在我运行时运行良好。如果将python代码替换为
print dir(my_object_model)会得到什么? -
你是绝对正确的@Cobbal!?当我把这个确切的代码放在新的解决方案中时它工作正常!?!我现在很困惑...将发布我的确切代码...
标签: c# hosting ironpython