C#如何通过反射设置StructLayoutAttribute.Pack?我通过反射动态创建C#结构,当我在调试器中检查结构的类型时,我注意到StructLayoutAttribute.Pack默认为8。我想将Pack设置为1。基本上,我想通过将此属性添加到结构的声明来完成反射:[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]I我在创建类型后尝试使用反射,但由于StructLayoutAttribute属性没有Setter,因此抛出异常。我的直觉是它需要在调用ModuleBuilder.DefineType时发生(我当前正在设置LayoutKind等),但我没有看到任何明显的对应TypeAttribute。任何指针表示赞赏。这里有完整的课程代码:usingSystem;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用System.Reflection;使用System.Reflection.Emit;namespaceAcmeCo.Serializable{publicclassDynamicSimStructBuilder{privatestaticTypestructType;publicstaticobjectGetStructInstance(){objectptInstance=Activator.CreateInstance(GetStruct(),newobject[]{});返回点实例;}publicstaticTypeGetStruct(){if(structType!=null){returnstructType;}AppDomainmyDomain=AppDomain.CurrentDomain;AssemblyNamemyAsmName=newAssemblyName("MyDynamicAssembly");AssemblyBuildermyAsmBuilder=myDomain.DefineDynamicAssembly(myAsmName,AssemblyBuilderAccess.RunAndSave);ModuleBuilderstructModule=myAsmBuilder.DefineDynamicModule("StructModule","MyDynamicAssembly.dll");TypeBuilderstructTypeBld=structModule.DefineType("AcmeCo.ThirdPartyAPIWrapper.DyanmicStruct",TypeAttributes.Public|TypeAttributes.Sealed|TypeAttributes.SequentialLayout|类型属性。可序列化|TypeAttributes.AnsiClass,typeof(ValueType));//使用XML文件中定义的一组变量在structThirdPartyAPIVariableCollection上创建字段collection=ThirdPartyAPIVariableCollection.Deserialize();foreach(集合中的ThirdPartyAPIVariable变量。ThirdPartyAPIVariables){FieldBuilderfield=structTypeBld.DefineField(variable.Name,Type.GetType(variable.SystemDataType,true),FieldAttributes.Public);}//基类和基类构造函数。输入objType=Type.GetType("System.Object");ConstructorInfoobjCtor=objType.GetConstructor(newType[]{});类型[]ctorParams={};ConstructorBuilderpointCtor=structTypeBld.DefineConstructor(MethodAttributes.Public,CallingConventions.Standard,ctorParams);ILGeneratorctorIL=pointCtor.GetILGenerator();//构建构造函数。首先调用基类//构造函数。构造函数的零索引参数//是新实例。存储字段的值。ctorIL.Emit(OpCodes.Ldarg_0);ctorIL.Emit(OpCodes.Call,objCtor);ctorIL.Emit(OpCodes.Ret);//创建类型,然后创建该类型的实例//(或者不,注释掉CreateInstance行没有坏处...)TypeptType=structTypeBld.CreateType();objectptInstance=Activator.CreateInstance(ptType,newobject[]{});DynamicSimStructBuilder.structType=ptType;intsizeOfNewData=System.Runtime.InteropServices.Marshal.SizeOf(ptType);Console.WriteLine("新类型是:"+sizeOfNewData);//将新创建的类型保存到DLL中供以后使用//(或者不,注释掉下一行也无妨...)myAsmBuilder.Save("MyDynamicAssembly.dll");返回点类型;}}}貌似加个参数可以指定包大小:来自http://msdn.microsoft.com/en-us/library/eyzw8bhy.aspx:以上是C#学习教程:HowdoesC#setStructLayoutAttribute。通过反射打包?分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——publicTypeBuilderDefineType(stringname,TypeAttributesattr,Typeparent,PackingSizepacksize)本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
