
Marshaling a structure containing a aray of different structures
Mike,
I believe that it comes down to the fact that there is no descriptor
telling the length of the array after the marshalling has occured.
SAFEARRAYS have a length descriptor embedded in them, so you can marshal
them anywhere you want really. However, with C-style arrays, there is
nothing that tells the interop layer how many items are in the array
embedded in the structure, so you can't know how much memory to read from
the address passed back.
For more information, you can look at the section of the .NET framework
documentation titled "Default Marshaling for Arrays".
--
- Nicholas Paldino [.NET MVP]
Quote:
> Thanks Nicholas. Is there a document on MSDN that explains why this cant
be
> done?
> -Mike
wrote
> > Mike,
> > Unfortunately, that is as about as elegant as it gets. The only
thing
> > that might help would be to use the StructureToPtr method on the Marshal
> > class to marshal the structure to unmanaged memory for you instead of
> doing
> > it yourself. You will still have to allocate the unmanged memory.
> > Hope this helps.
> > --
> > - Nicholas Paldino [.NET MVP]
> > > Hi,
> > > Im trying to marshal a structure that contains an array of another
> > > structure. As you can see the tNSPropertyList contains an array of
> > > tNSProperty structures. I have been able to make this work by copying
> all
> > > the array values to an allocated memory buffer, then passing the
pointer
> > to
> > > that memory in place of the array, but Im hoping someone out there
knows
> > of
> > > a more elegant solution.
> > > typedef struct _tNSProperty {
> > > LPCWSTR pName;
> > > DWORD dwType;
> > > LPCWSTR pValue;
> > > } tNSProperty;
> > > typedef struct _tNSPropertyList {
> > > tNSProperty Property;
> > > struct _tNSPropertyList *pNext;
> > > } tNSPropertyList;
> > > I have tried doing this, but I get a System.TypeLoadException at
runtime
> > > complaining about the array member.
> > > [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
> > > public class tNSProperty
> > > {
> > > public string Name; // LPCWSTR Name
> > > public uint Type; // DWORD Type
> > > public string Value; // LPCWSTR pValue
> > > }
> > > [StructLayout(LayoutKind.Sequential)]
> > > public class tNSPropertyList
> > > {
> > > public uint PropertyCount; // DWORD PropertyCount
> > > public tNSProperty[] Properties; // tNSProperty *Properties
> > > }
> > > TIA
> > > -Mike