我正在使用dnLib从我正在编写的自定义语言CSASM动态生成MSIL程序集:
string absolute = Path.Combine(Directory.GetCurrentDirectory(), forceOutput ?? $"{asmName}.exe");
ModuleDefUser mod = new ModuleDefUser(asmName, Guid.NewGuid(), new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName))){
Kind = ModuleKind.Console,
RuntimeVersion = "v4.0.30319" //Same runtime version as "CSASM.Core.dll"
};
var asm = new AssemblyDefUser($"CSASM_program_{asmName}", new Version(version));
asm.Modules.Add(mod);
// Adding attribute code omitted for brevity
//Adds types to the module and constructs methods and method bodies for those types based on the CSASM source file in question
Construct(mod, source);
mod.Write(absolute);可执行文件的生成正在按预期进行。
但是,当试图运行此可执行文件时,将引发下面的TypeLoadException:
System.TypeLoadException: Could not load type 'CSASM.Core.IntPrimitive' from assembly
'CSASM_program_Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' due to
value type mismatch.
at Example.Program.csasm_main()CSASM_program_Example是生成的可执行文件Example.exe的程序集名称。
实际上,IntPrimitive类型可以在CSASM.Core.dll程序集中找到,该程序集与生成的可执行文件位于同一个文件夹中。
由于缺乏关于dnLib的文档,我基本上是在黑暗中蹒跚而行。
简而言之,为什么类型试图从错误的程序集加载?
如果是的话,我有办法补救吗?
在dnSpy中查看程序集会显示TypeRef和MemberRef引用正确的程序集,这使得这种困境更加令人沮丧。
发布于 2021-03-17 18:13:15
在对dnLib DLL进行了非常彻底的检查之后,问题是由于我使用了Importer.ImportDeclaringType(Type).ToTypeDefOrRef(),导致值类型TypeSigs被注册为类类型的TypeSigs。
尽管文档要求对方法和字段声明使用Importer.ImportDeclaringType(Type) over Importer.ImportAsTypeSig(Type),但您确实不应该使用它。
https://stackoverflow.com/questions/66480908
复制相似问题