| Pierre Greborio |
Dimensione di una struttura
Ciao a tutti,
ho un problema di interoperability. Ho creato una struttura contenente un vettore statico: [StructLayout(LayoutKind.Sequential)] struct MiaStruttura { ushort valA; [MarshalAs(UnmanagedType.LPArray, SizeConst=10)] ushort[] valB; } ho la necessità di ricavare la dimensione della struttura: Console.WriteLine(Marshal.SizeOf(typeof(MiaStruttura))); IL messaggio d'errore dice che la struttura non può essere marshaled come unmanaged. Suggerimenti ? Ciao Pierre |
| Pierre Greborio |
Re: Dimensione di una struttura
Trovato l'arcano. Il problema consiste nel fatto che una struct è un value type mentre un array è un reference type. Per risolvere il problema si potrebbe inizializzare attraverso un construttore (con parametro) oppure un metodo che inizializzano gli array. Questa soluzione non è del tutto elegante, l'alternativa è costruirsi un tipo inline in questo modo:
struct MyStruct { public int A; // questo è un vettore di int di lunghezza 10 public MyArray B; [StructLayout(LayoutKind.Explicit)] public struct MyStruct { public const int dataLength = 10; [FieldOffset(0)] private int Header; [FieldOffset(dataLength - 1)] private int Footer; public int Length { get { return dataLength; } } public unsafe int this[int index] { get { if( (index < 0) || (index >= dataLength) ) throw new IndexOutOfRangeExcpression(); fixed(int *head = &Header) return *(head + index); } set { if( (index < 0) || (index >= dataLength) ) throw new IndexOutOfRangeExcpression(); fixed(int *head = &Header) *(head + index) = value; } } } } In questo modo si accede direttamente alle celle di memoria del vettore senza richiedere un'inizializzazione. |