解决System.Runtime.InteropServices.MarshalDirectiveException: 结构体字段 Int32[] 无法作为 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. \n\nThe 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. \n\nTo 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. \n\nHere's an example of how you can fix the issue: \n\ncsharp \n[StructLayout(LayoutKind.Sequential)] \npublic struct MyStruct \n{ \n\tpublic IntPtr Data; \n\tpublic int Length; \n} \n\n// ... \n\nint[] array = new int[10]; \nMyStruct myStruct = new MyStruct(); \nmyStruct.Length = array.Length; \n\n// Allocate unmanaged memory for the array \nmyStruct.Data = Marshal.AllocHGlobal(array.Length * sizeof(int)); \n\n// Copy the managed array to the unmanaged memory \nMarshal.Copy(array, 0, myStruct.Data, array.Length); \n\n// Use the myStruct... \n\n// Free the unmanaged memory \nMarshal.FreeHGlobal(myStruct.Data); \n \n\nIn 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. \n\nBy manually marshaling the array, you can avoid the MarshalDirectiveException.
原文地址: https://www.cveoy.top/t/topic/qvT0 著作权归作者所有。请勿转载和采集!