diff --git a/PInvoke/Shared/StructHelper.cs b/PInvoke/Shared/StructHelper.cs index 127bed11..a5bc2d93 100644 --- a/PInvoke/Shared/StructHelper.cs +++ b/PInvoke/Shared/StructHelper.cs @@ -1,5 +1,8 @@ using System; +using System.Linq; +using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using Vanara.Extensions; namespace Vanara.PInvoke @@ -39,5 +42,21 @@ namespace Vanara.PInvoke if (count == 0) return new T[0]; return DangerousAddressOf(ref fieldReference).ToArray(count, offset); } + + /// Creates a new instance of with a size field set to the size of its unmanaged type. + /// The type to return . + /// + /// Name of the field which is assigned the size. If , the first public or private field is used. + /// + /// An initialized instance of . + public static T InitWithSize(string fieldName = null) where T : new() + { + const BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + var fi = fieldName is null ? typeof(T).GetOrderedFields(bf).FirstOrDefault() : typeof(T).GetField(fieldName, bf); + var ret = (object)new T(); + fi.SetValue(ret, Convert.ChangeType((uint)InteropExtensions.SizeOf(), fi.FieldType)); + return (T)ret; + } } } \ No newline at end of file