Search code examples
c#marshallingdllimportoutofrangeexception

Marshal.Copy Throws ArgumentOutOfRangeException


I'm trying to marshal data from managed memory in my C# application to an unmanaged memory location for use by a proprietary DLL. The value is a float, but the DLL requires a pointer to a float. In the constructor, the my idea was to assign unmanaged memory to the pointer, and then copy the passed-in float value to the unmanaged memory.

internal class MyInternalClass
{
    private static float[] fltArry;

    public struct MY_DLL_STRUCT
    {
        public IntPtr fltPtr;

        public MY_DLL_STRUCT(float flt)
        {
            MyInternalClass.fltArry = new float[] { flt };
            this.fltPtr = Marshal.AllocHGlobal(sizeof(float) * MyInternalClass.fltArry.Length);
            Marshal.Copy(MyInternalClass.fltArry, 0, this.fltPtr, sizeof(float) * MyInternalClass.fltArry.Length);
        }
    }
}

The sizes look good to me, but whenever the Marshal.Copy function is called an ArgumentOutOfRangeException is thrown. Any ideas?


Solution

  • The last parameter to Marshal.Copy is the number of elements to copy.

    I suspect you should use 1 (or MyInternalClass.fltArry.Length) rather than sizeof(float) * MyInternalClass.fltArry.Length. You are passing a value too large, thus:

    Exceptions

    ArgumentOutOfRangeException - startIndex and length are not valid.