如何在IronPython中调用C#/ .NET命名空间?

问题描述 投票:1回答:1

我想在IronPython中复制以下内容,到目前为止搜索一直没有结果和/或令人失望。

namespace Groceries
{
     public class ChocolateMilk : Milk
     {
          // Other stuff here
     }
}

想法是编译的Python DLL将通过System.Reflection.Assembly.Load加载到C#程序中,并且加载的DLL上的GetType(“Groceries.ChocolateMilk”)不会返回null。

我能找到的最新答案是在2008年,并表示如果不使用Hosting API - http://lists.ironpython.com/pipermail/users-ironpython.com/2008-October/008684.html就不可能。

任何关于如何实现这一点的建议将不胜感激。目前通过IronPython无法做出的任何结论也将受到赞赏,但不那么重要。

c# namespaces ironpython
1个回答
4
投票

我对你在这里问的问题有点困惑。您是否尝试在IronPython模块中实例化C#代码?或者您是否有使用IronPython编写的等效类,并且您希望在C#代码中实例化它们?

根据您发布的链接,我想您将选择后者,并且您希望在C#代码中实例化IronPython类。答案是,你无法直接实例化它们。将IronPython代码编译为程序集时,不能使用常规.NET代码中定义的类型,因为IronPython类和.NET类之间没有一对一的映射。您必须在C#项目中托管程序集并以这种方式实例化它。

考虑这个模块,Groceries.py编译为驻留在工作目录中的Groceries.dll

class Milk(object):
    def __repr__(self):
        return 'Milk()'

class ChocolateMilk(Milk):
    def __repr__(self):
        return 'ChocolateMilk()'

要在C#代码中托管模块:

using System;

using IronPython.Hosting;
using System.IO;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        var engine = Python.CreateEngine();
        var groceriesPath = Path.GetFullPath(@"Groceries.dll");
        var groceriesAsm = Assembly.LoadFile(groceriesPath);
        engine.Runtime.LoadAssembly(groceriesAsm);

        dynamic groceries = engine.ImportModule("Groceries");
        dynamic milk = groceries.ChocolateMilk();
        Console.WriteLine(milk.__repr__()); // "ChocolateMilk()"
    }
}

否则以另一种方式在IronPython代码中创建.NET类型的实例(如标题所示)。您需要添加程序集的路径,引用它,然后您可以根据需要实例化它。

# add to path
import sys
sys.path.append(r'C:\path\to\assembly\dir')

# reference the assembly
import clr
clr.AddReferenceToFile(r'Groceries.dll')

from Groceries import *
chocolate = ChocolateMilk()
print(chocolate)
© www.soinside.com 2019 - 2024. All rights reserved.