を使用して P/Invoke の構造体を動的に構築します
const TypeAttributes typeAttributes = TypeAttributes.Public |
TypeAttributes.SequentialLayout |
TypeAttributes.UnicodeClass;
var typeBuilder = moduleBuilder.DefineType("MyType", typeAttributes, typeof(ValueType));
その後、次のように を構築StructLayoutAttribute
して型に追加します
ConstructorInfo structLayoutAttributeConstructorInfo = typeof(StructLayoutAttribute).GetConstructor(new[] { typeof(LayoutKind) });
FieldInfo charSetFieldInfo = typeof(StructLayoutAttribute).GetField(nameof(StructLayoutAttribute.CharSet));
CustomAttributeBuilder attr = new CustomAttributeBuilder(structLayoutAttributeConstructorInfo,
new object[] { LayoutKind.Sequential },
new FieldInfo[] { charSetFieldInfo },
new object[] { CharSet.Unicode });
typeBuilder.SetCustomAttribute(structLayoutAttributeBuilder);
これは設定に相当します
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
これで、構造体に を適用するかどうかに関係なく、コードは完全に正常StructLayoutAttribute
に動作します。
TypeAttribute.SequentialLayout
明示的な属性の設定とフラグの使用の違いは何ですか?
一見、属性の設定は不必要な冗長性であるか、何か不足していますか?