问题描述:

I created a dummy DLL. I was expecting I can access S1 in the namespace. I can see my function and I can see the struct with il dasm when its in exe form.

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");

}

}

}

}

网友答案:

I'm not sure I understand what exactly are you asking, but I think the problem is that you're always defining the module as HelloWorld.exe. What you need to do is to make sure the module name matches the file name.

So, if you want to save the assembly as HelloWorld.dll, then you need to set the module name to HelloWorld.dll too.

相关阅读:
Top