Нет доступа к DLL при создании IL Generator

Я создал фиктивную DLL. Я ожидал, что смогу получить доступ S1 в пространстве имен. Я вижу свою функцию и могу видеть структуру с il dasm, когда она находится в exe-форме.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;
using System.Threading;
using System.Diagnostics.SymbolStore;
using System.IO;

namespace emitTest
{
    class Program
    {
        static void Main(string[] args)
        {
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = "HelloWorld";
            AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder module;
            module = assemblyBuilder.DefineDynamicModule("HelloWorld.exe", true);
            TypeBuilder typeBuilder = module.DefineType("MyNamespace.HelloWorldType", TypeAttributes.Public | TypeAttributes.Class);
            MethodBuilder methodbuilder = typeBuilder.DefineMethod("Main", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(string[]) });
            var s1 = module.DefineType("Space.S1", TypeAttributes.Public | TypeAttributes.Sealed |  TypeAttributes.AnsiClass | TypeAttributes.SequentialLayout | TypeAttributes.BeforeFieldInit, typeof(System.ValueType));
            s1.DefineField("a", typeof(int), FieldAttributes.Public);
            s1.CreateType();
            ILGenerator ilGenerator = methodbuilder.GetILGenerator();
            ilGenerator.Emit(OpCodes.Ret);
            Type helloWorldType = typeBuilder.CreateType();
            if (false)
            {
                // set the entry point for the application and save it
                assemblyBuilder.SetEntryPoint(methodbuilder, PEFileKinds.ConsoleApplication);
                assemblyBuilder.Save("HelloWorld.exe");
            }
            else
            {
                assemblyBuilder.SetEntryPoint(methodbuilder, PEFileKinds.Dll);
                assemblyBuilder.Save("HelloWorld.dll");
            }
        }
    }
}

1 ответ

Решение

Я не уверен, что понимаю, что именно вы спрашиваете, но я думаю, что проблема в том, что вы всегда определяете модуль как HelloWorld.exe, Вам нужно убедиться, что имя модуля совпадает с именем файла.

Итак, если вы хотите сохранить сборку как HelloWorld.dll, тогда вам нужно установить имя модуля в HelloWorld.dll тоже.

Другие вопросы по тегам