Skip to main content
 首页 » 编程设计

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

2024年02月23日15youxin

我希望在 IronPython 中复制以下内容,但迄今为止搜索没有结果和/或令人失望。

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

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

我能找到的最新答案是在 2008 年,它说不使用托管 API 是不可能的 - http://lists.ironpython.com/pipermail/users-ironpython.com/2008-October/008684.html .

如有任何关于如何实现此目的的建议,我们将不胜感激。任何目前无法通过 IronPython 完成的结论也将受到赞赏,但不那么重要。

请您参考如下方法:

我对你在这里问的问题有点困惑。您是否尝试在 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)