使用mono调用C#中的IronPython对象

我有以下Iron Python代码.

class Hello:
    def __init__(self):
        pass
    def add(self,x,y):
        return (x+y)

我需要从C#调用它,我想出了以下代码.

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

class Hello {
    public static void Main()
    {
        ScriptEngine engine = Python.CreateEngine();
        ScriptSource script = engine.CreateScriptFromSourceFile("myPythonScript.py");
        ScriptScope scope = engine.CreateScope();

        script.Execute(scope);
    }
}

复制IronPython.dll后,我运行以下命令. (我试图运行gacutil,但我得到了一些errors.

 dmcs /r:IronPython.dll callipy.cs

但是我得到了一些错误信息,如下所示.

Could not load file or assembly 'Microsoft.Scripting.ExtensionAttribute,Version=2.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
Missing method .ctor in assembly /Users/smcho/Desktop/cs/namespace/IronPython.dll,type System.Runtime.CompilerServices.ExtensionAttribute
Can't find custom attr constructor image: /Users/smcho/Desktop/cs/namespace/IronPython.dll mtoken: 0x0a000080
Could not load file or assembly 'Microsoft.Scripting.Core,Version=1.0.0.0,PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
Could not load file or assembly 'Microsoft.Scripting.Core,PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
...

似乎IronPython需要Microsoft.Scipting.Core,但是使用mono我不知道该怎么办?

> C#可以在Mono上运行IronPython对象吗?如果是这样,怎么办?

解决方法

IronPython不是一个独立的DLL.它有一些应该与IronPython一起提供的依赖项(它们包含在针对.NET 2.0的最新压缩分发中 – 请参阅 IronPython download page):

IronPython.Modules.dll
Microsoft.Dynamic.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Core.dll
Microsoft.Scripting.Debugging.dll
Microsoft.Scripting.ExtensionAttribute.dll

确保您的项目可以找到这些DLL(它目前无法找到,这就是您收到错误的原因).我从来没有尝试过在Mono上运行IronPython,但它是should work.

请注意,针对.NET 4.0的IronPython版本不包含(或需要)Microsoft.Scripting.Core.dll和Microsoft.Scripting.ExtensionAttribute.dll,因为它们的功能已合并到System.Core中.有关详细信息,请参见this answer.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...