SystemRuntimeInteropServicesMarshalDirectiveException Structure field of type Int32 cant be marshalled as LPArray
This exception occurs when trying to marshal a structure field of type Int32 array using LPArray attribute. The LPArray attribute is used to marshal a managed array as a pointer to an unmanaged array.
The problem is that the LPArray attribute cannot be applied to a structure field of array type. It is only valid for method parameters or fields in classes.
To fix this issue, you need to change the type of the structure field to IntPtr, and manually marshal the array using the Marshal.Copy method.
Here's an example of how you can fix the issue:
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
public IntPtr Data;
public int Length;
}
// ...
int[] array = new int[10];
MyStruct myStruct = new MyStruct();
myStruct.Length = array.Length;
// Allocate unmanaged memory for the array
myStruct.Data = Marshal.AllocHGlobal(array.Length * sizeof(int));
// Copy the managed array to the unmanaged memory
Marshal.Copy(array, 0, myStruct.Data, array.Length);
// Use the myStruct...
// Free the unmanaged memory
Marshal.FreeHGlobal(myStruct.Data);
In this example, we changed the type of the structure field Data to IntPtr. Then, we allocated unmanaged memory using Marshal.AllocHGlobal and copied the array to the unmanaged memory using Marshal.Copy. Finally, we freed the unmanaged memory using Marshal.FreeHGlobal.
By manually marshaling the array, you can avoid the MarshalDirectiveException
原文地址: https://www.cveoy.top/t/topic/iPOo 著作权归作者所有。请勿转载和采集!