MarshalAsAttribute.SizeParamIndex Field

Definition

Indicates the zero-based parameter that contains the count of array elements, similar to size_is in COM.

C#
public short SizeParamIndex;

Field Value

Examples

C#
using System.Runtime.InteropServices;
using SomeNamespace;

namespace SomeNamespace
{
    // Force the layout of your fields to the C style struct layout.
    // Without this, the .NET Framework will reorder your fields.
    [StructLayout(LayoutKind.Sequential)]
    public struct Vertex
    {
        float	x;
    float	y;
        float	z;
    }

    class SomeClass
    {
        // Add [In] or [In, Out] attributes as approppriate.
        // Marshal as a C style array of Vertex, where the second (SizeParamIndex is zero-based)
        //  parameter (size) contains the count of array elements.
        [DllImport ("SomeDll.dll")]
        public static extern void SomeUnsafeMethod(
                                      [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] Vertex[] data,
                                      long size );

        public void SomeMethod()
        {
            Vertex[] verts = new Vertex[3];
            SomeUnsafeMethod( verts, verts.Length );
        }
    }
}

class Test
{
    public static void Main()
    {
        SomeClass AClass = new SomeClass();

        AClass.SomeMethod();
    }
}

Remarks

The SizeParamIndex field supports managed-to-unmanaged and unmanaged-to-managed calls. It does not have any effect on managed code that calls COM objects.

Depending on the managed type and the attributes applied to it, the array can be passed as a safe array or C-style array.

When arrays are passed as C-style arrays, the marshaler cannot determine the size of the array. Therefore, to pass an managed array to an unmanaged function or method, you must provide two arguments:

  • The array, defined by reference or value.

  • The array size, defined by reference or value.

The zero-based index of the array size parameter is defined by using the SizeParamIndex field.

If you specify both SizeParamIndex and MarshalAsAttribute.SizeConst with a UnmanagedType.LPArray field, the sum of the fields' values produces a size total.

For more information, see Default Marshaling for Arrays.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also