【问题标题】:Python for .NET: Using same .NET assembly in multiple versionsPython for .NET:在多个版本中使用相同的 .NET 程序集
【发布时间】:2023-09-29 01:16:01
【问题描述】:

我的问题:我有 2 个版本的程序集,并希望在我的 Python 项目中同时使用它们。

.NET 库安装在 GAC (MSIL) 中,具有相同的公共令牌:

lib.dll (1.0.0.0)
lib.dll (2.0.0.0)

在 Python 中我想要这样的东西:

import clr
clr.AddReference("lib, Version=1.0.0.0, ...")
from lib import Class
myClass1 = Class()
myClass1.Operation()

*magic*

clr.AddReference("lib, Version=2.0.0.0, ...")
from lib import class
myClass2 = Class()
myClass2.Operation()
myClass2.OperationFromVersion2()

*other stuff*

# both objects should be accessibly
myClass1.Operation() 
myClass2.OperationFromVersion2()

有没有办法做到这一点?与 AppDomains 或 bindingRedirect 有关吗?

注意:当然 myClass1.operationFromVersion2() 可能会失败...

【问题讨论】:

  • 如何将 2 个版本的程序集添加到 .NET 中的引用?
  • 我可以在那里使用反射。

标签: c# python .net ironpython python.net


【解决方案1】:

我找到了一个解决方案:Python for .NET 也支持反射!

代替

clr.AddReference("lib, Version=1.0.0.0, ...")

你必须使用

assembly1 = clr.AddReference("lib, Version=1.0.0.0, ...")

通过该程序集,您可以使用 C# 中的所有反射功能。在我的示例中,我必须使用以下代码(版本 2 相同):

from System import Type
type1 = assembly1.GetType(...)
constructor1 = type1.GetConstructor(Type.EmptyTypes)
myClass1 = constructor1.Invoke([])

【讨论】:

  • 这是一个很好的答案,当然应该添加到 pythonnet 文档中!
【解决方案2】:

我无法使用接受的答案使其正常工作。这是我的解决方案。

您必须直接使用 .NET 框架,而不是使用 PythonNet:

import System

dll_ref = System.Reflection.Assembly.LoadFile(fullPath)
print(dll_ref.FullName)
print(dll_ref.Location)

检查是否使用了正确的 DLL。

要使用具有相同版本的多个 DLL,只需将其加载到另一个变量中

another_dll_ref = System.Reflection.Assembly.LoadFile(anotherFullPath)

现在您可以使用指定 dll 中的对象了。

公共非静态类的实例

some_class_type = dll_ref.GetType('MyNamespace.SomeClass')
my_instance = System.Activator.CreateInstance(some_class_type)
my_instance.a = 4 # setting attribute
my_instance.b('whatever') # calling methods

在公共静态类中调用方法

some_class_type = dll_ref.GetType('MyNamespace.SomeClass')
method = some_class_type.GetMethod('SomeMethod')
# return type and list of parameters
method.Invoke(None, [1, 2.0, '3']) 

创建结构实例

some_struct_type = dll_ref.GetType('MyNamespace.SomeStruct')
my_struct = System.Activator.CreateInstance(some_struct_type)
my_struct.a = 3

(取自我的问题Python for .NET: How to explicitly create instances of C# classes using different versions of the same DLL?

【讨论】:

    最近更新 更多