Marshal.Copy 抛出 ArgumentOutOfRangeException
Marshal.Copy Throws ArgumentOutOfRangeException
我正在尝试将数据从我的 C# 应用程序中的托管内存编组到非托管内存位置,以供专有 DLL 使用。该值是一个浮点数,但 DLL 需要一个指向浮点数的指针。在构造函数中,我的想法是将非托管内存分配给指针,然后将传入的float值复制到非托管内存中。
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);
}
}
}
尺寸对我来说很好,但是每当调用 Marshal.Copy
函数时,都会抛出 ArgumentOutOfRangeException
。有什么想法吗?
Marshal.Copy
的最后一个参数是 number of elements to copy。
我怀疑您应该使用 1
(或 MyInternalClass.fltArry.Length
)而不是 sizeof(float) * MyInternalClass.fltArry.Length
。您传递的值太大,因此:
Exceptions
ArgumentOutOfRangeException - startIndex and length are not
valid.
我正在尝试将数据从我的 C# 应用程序中的托管内存编组到非托管内存位置,以供专有 DLL 使用。该值是一个浮点数,但 DLL 需要一个指向浮点数的指针。在构造函数中,我的想法是将非托管内存分配给指针,然后将传入的float值复制到非托管内存中。
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);
}
}
}
尺寸对我来说很好,但是每当调用 Marshal.Copy
函数时,都会抛出 ArgumentOutOfRangeException
。有什么想法吗?
Marshal.Copy
的最后一个参数是 number of elements to copy。
我怀疑您应该使用 1
(或 MyInternalClass.fltArry.Length
)而不是 sizeof(float) * MyInternalClass.fltArry.Length
。您传递的值太大,因此:
Exceptions
ArgumentOutOfRangeException - startIndex and length are not valid.