如何在 IronPython 中调用 C#/.NET 命名空间?
我希望在 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 实现这一点的结论也将受到赞赏,但不那么如此。
I'm looking to replicate the following in IronPython and searching has so far been fruitless and/or disappointing.
namespace Groceries
{
public class ChocolateMilk : Milk
{
// Other stuff here
}
}
The idea would be that the compiled Python DLL will be loaded into a C# program through System.Reflection.Assembly.Load and a GetType("Groceries.ChocolateMilk") on the loaded DLL would not return null.
The most recent answer I was able to find was in 2008 and said that it was impossible without using the Hosting API - http://lists.ironpython.com/pipermail/users-ironpython.com/2008-October/008684.html.
Any suggestions on how to accomplish this would be greatly appreciated. Any conclusions that this is currently impossible to do via IronPython will also be appreciated, but less so.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对你在这里问的问题有点困惑。您是否尝试在 IronPython 模块中实例化该 C# 代码?或者您是否有用 IronPython 编写的等效类,并且想要在 C# 代码中实例化它们?
根据您发布的链接,我想您会选择后者,并且拥有要在 C# 代码中实例化的 IronPython 类。答案是,你不能直接实例化它们。当您将 IronPython 代码编译为程序集时,您无法将其中定义的类型与常规 .NET 代码一起使用,因为 IronPython 类和 .NET 类之间不存在一对一的映射。您必须在 C# 项目中托管程序集并以这种方式实例化它。
考虑这个模块,
Groceries.py
编译为Groceries.dll
驻留在工作目录中:要在 C# 代码中托管该模块:
否则,请采用其他方式并创建一个IronPython 代码中 .NET 类型的实例(如标题所示)。您需要将路径添加到程序集,引用它,然后可以根据需要实例化它。
I'm a bit confused on what you're asking here. Are you trying to instantiate that C# code in your IronPython modules? Or do you have the equivalent classes written in IronPython and you want to instantiate them in your C# code?
Based on the link you posted, I suppose you're going for the latter and have IronPython classes that you want instantiated in your C# code. The answer is, you cannot directly instantiate them. When you compile IronPython code to an assembly, you cannot use the types defined there with your regular .NET code since there is not a one-to-one mapping between IronPython classes and .NET classes. You would have to host the assembly in your C# project and instantiate it that way.
Consider this module,
Groceries.py
compiled toGroceries.dll
residing in the working directory:To host the module in your C# code:
Otherwise to go the other way and create an instance of your .NET type in your IronPython code (as your title suggests). You'd need to add the path to your assembly, reference it, then you could instantiate it as needed.