c# - dnLib 生成的程序集 - 运行时抛出 TypeLoadException
问题描述
我正在使用dnLib从我正在编写的自定义语言中动态生成 MSIL 程序集,名为 CSASM:
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
s 和MemberRef
s 引用了正确的程序集,这使这种困境更加令人沮丧。
解决方案
在对 dnLib DLL 进行了非常彻底的检查后,问题是由于我使用Importer.ImportDeclaringType(Type).ToTypeDefOrRef()
,这导致 value-type TypeSig
s 被注册为 class-type TypeSig
s。
即使文档说要使用Importer.ImportDeclaringType(Type)
overImporter.ImportAsTypeSig(Type)
方法和字段声明,你真的不应该使用它。
推荐阅读
- api - 如何在 ApiResource 中使用 PUT 和 DELETE?
- react-native - 反应本机没有接收到带有套接字 io 的连接回调
- wcf - 用于 HTTPS 与 HTTP 的 IIS 的 WCF 绑定问题 绑定实例已关联以进行侦听
- html - 如何为图像的 css-border 分配动态颜色?
- python - 使用 Celery 对用户执行定期任务或使用 Celery Beat 迭代所有用户
- php - JSONArray 未显示在回收站视图中
- python - 需要使用 Pyspark 处理 2 亿条记录
- android - Android中的transclusion等价物
- php - 如何在查询中使用最新日期作为条件
- sql-server - 我们如何检查 SQL Server 数据库中是否有非零数据?