了解对象在gc堆中的布局是很有用的。在垃圾收集期间,有效的对象是通过递归访问对象来标记的,这些对象从堆栈的根和句柄开始。但是,从每个堆段的开始到结束,对象的位置以一种有组织的方式排列也很重要。!DumpHeap命令依赖于这个逻辑组织来正确地遍历堆,如果它报告了一个错误,可以打赌您的堆出了问题。

下面是代码

usingSystem;usingSystem.Reflection;usingSystem.Reflection.Emit;usingSystem.Threading;usingSystem.Runtime.InteropServices;public classEmitHelloWorld
{

[DllImport(
"kernel32")]public static extern voidDebugBreak();static void Main(string[] args)
{
//create a dynamic assembly and module AssemblyName assemblyName = newAssemblyName();
assemblyName.Name
= "HelloWorld";
AssemblyBuilder assemblyBuilder
=Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder module;
module
= assemblyBuilder.DefineDynamicModule("HelloWorld.exe");//create a new type to hold our Main method TypeBuilder typeBuilder = module.DefineType("HelloWorldType", TypeAttributes.Public |TypeAttributes.Class);//create the Main(string[] args) method MethodBuilder methodbuilder = typeBuilder.DefineMethod("Main", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(string[]) });//generate the IL for the Main method ILGenerator ilGenerator =methodbuilder.GetILGenerator();
ilGenerator.EmitWriteLine(
"hello, world");
ilGenerator.Emit(OpCodes.Ret);
//bake it Type helloWorldType =typeBuilder.CreateType();//run it helloWorldType.GetMethod("Main").Invoke(null, new string[] {null});

DebugBreak();
//set the entry point for the application and save it assemblyBuilder.SetEntryPoint(methodbuilder, PEFileKinds.ConsoleApplication);
assemblyBuilder.Save(
"HelloWorld.exe");
}
}

标签: none

添加新评论