I am having trouble marshalling an array of structures as output parameters.
What am I doing wrong? I assume that when I marshall an array I do not need
the ref attribute since an array is an object. Is this correct? If
correct, then passing an array is the same no matter if it is an in or an
out parameter. Here is my code...
[StructLayout(LayoutKind.Sequential, Pack=8, CharSet=CharSet.Ansi)]
internal struct MATCH_INFO2 {
public int iNumColorants;
public int iBaseID;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=10)]
public int[] iColorantIDs;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=10)]
public float[] fAmount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=10)]
public float[] fColorantPercentages;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=31)]
public float[] fRefls;
public float fDE;
public float fMI;
public float fCFI;
public float fCost;
public float fOpacity;
public float fTotalAmount;
public float fBasePercentage;
};
// C API
extern "C" DLLAPI BOOL MRF(MATCH_INFO2* pResults);
[DllImport(m_strDLLName)]
private static extern int MRF( MATCH_INFO2[] Results );
Code usage...
MATCH_INFO2[] tMatchInfo = new MATCH_INFO2[5];
// I then initialize the array...
// Call the native function...
MRF( tMatchInfo );
David,
>What am I doing wrong? I assume that when I marshall an array I do not need
>the ref attribute since an array is an object. Is this correct?
Yes that's correct. But according to
http://msdn.microsoft.com/library/en-us/cpguide/html/cpconcopyingpinning.asp
"If a reference type is passed by value and it has members of
non-blittable types [...] To avoid unnecessarily copying and
conversion, these types are marshaled as In parameters. You must
explicitly apply the InAttribute and OutAttribute attributes to an
argument for the caller to see changes made by the callee."
So if you want data copied back you should change your declaration to
private static extern int MRF( [In, Out] MATCH_INFO2[] Results );
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
David Hoffer - 13 Apr 2004 00:34 GMT
Mattias,
Thanks for the help!
-dh
> David,
>
> >What am I doing wrong? I assume that when I marshall an array I do not need
> >the ref attribute since an array is an object. Is this correct?
>
> Yes that's correct. But according to
http://msdn.microsoft.com/library/en-us/cpguide/html/cpconcopyingpinning.asp
> "If a reference type is passed by value and it has members of
> non-blittable types [...] To avoid unnecessarily copying and
[quoted text clipped - 7 lines]
>
> Mattias