与程序集加载相反的操作(byte [] rawAssembly) [英] Opposite operation to Assembly Load(byte[] rawAssembly)
问题描述
我注意到有一个 System.Reflection.Assembly
方法,它是 Assembly Load(byte [] rawAssembly)
.
I notice that there is a method of System.Reflection.Assembly
, which is Assembly Load(byte[] rawAssembly)
.
我想知道是否有相反的操作,例如 byte [] Store(Assembly assembly)
.如果没有,如何将装配对象转换为 byte []
,以完全在内存中调用 Assembly Load(byte [] rawAssembly)
而不将装配写到文件中?谢谢!
I wonder if there is an opposite operation like byte[] Store(Assembly assembly)
. If not, how can I convert an assembly object to byte[]
for calling Assembly Load(byte[] rawAssembly)
totally in memory without writing the assembly to a file? Thanks!
注释:问题来自以下情况:我正在使用第三方库,该库将一个Assembly实例返回给我,并且我必须使用反射来调用其方法.我不知道该库如何创建此程序集对象.我只是想知道是否可以将程序集对象存储到byte []并用'Assembly Load(byte [] rawAssembly)'重新加载它.谢谢!
Comment: The question comes from the situation that I am using a third-party library which returns an Assembly instance to me, and I must use reflection to call its methods. I don't know how the library creates this assembly object. I just wonder if I can store the assembly object to byte[] and reload it with 'Assembly Load(byte[] rawAssembly)'. Thanks!
推荐答案
System.Security.Policy.Hash能够计算哈希值,而与程序集的位置无关.因此,我们至少有两种方法可以将程序集获取为字节数组:
System.Security.Policy.Hash is able to calculate a Hash regardless of the assembly's location. So we have at least 2 ways to obtain an assembly as a byte array:
1)使用反射:
var hash = new Hash(assembly);
var dllAsArray = (byte[]) hash.GetType()
.GetMethod("GetRawData", BindingFlags.Instance | BindingFlags.NonPublic)
.Invoke(hash, new object[0]);
2)使用伪造的HashAlgorithm实现:
2) Using a fake HashAlgorithm implementation:
public class GetWholeBodyPseudoHash : HashAlgorithm
{
protected override void Dispose(bool disposing)
{
if(disposing) _memoryStream.Dispose();
base.Dispose(disposing);
}
static GetWholeBodyPseudoHash()
{
CryptoConfig.AddAlgorithm(typeof(GetWholeBodyPseudoHash), typeof(GetWholeBodyPseudoHash).FullName);
}
private MemoryStream _memoryStream=new MemoryStream();
public override void Initialize()
{
_memoryStream.Dispose();
_memoryStream = new MemoryStream();
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
_memoryStream.Write(array, ibStart, cbSize);
}
protected override byte[] HashFinal()
{
return _memoryStream.ToArray();
}
}
...
var bytes = new Hash(yourAssembly).GenerateHash(new GetWholeBodyPseudoHash());
这篇关于与程序集加载相反的操作(byte [] rawAssembly)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!