IronPython 2.7.4公开应用程序对象模型

时间:2014-09-29 13:31:45

标签: c# hosting ironpython

我试图运行基本托管"公开应用程序对象模型"来自IronPython doc的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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要将Program公开以及内部类。由于我不完全确定的原因,所有包含的课程必须是公开的,否则IronPython将无法与您的班级进行互动。