【问题标题】:dnLib-Generated Assembly - TypeLoadException Thrown at RuntimednLib 生成的程序集 - 运行时抛出 TypeLoadException
【发布时间】:2023-03-18 07:25:02
【问题描述】:

我正在使用 dnLib 从我正在编写的自定义语言(名为 CSSM)动态生成 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 中查看程序集显示 TypeRefs 和 MemberRefs 引用了正确的程序集,这使这种困境更加令人沮丧。

【问题讨论】:

    标签: c# cil dnlib


    【解决方案1】:

    在对 dnLib DLL 进行了非常彻底的检查后,问题是由于我使用了Importer.ImportDeclaringType(Type).ToTypeDefOrRef(),导致值类型TypeSigs 被注册为类类型TypeSigs。

    尽管文档说要使用 Importer.ImportDeclaringType(Type) 而不是 Importer.ImportAsTypeSig(Type) 来声明方法和字段,但您确实不应该使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多