我有以下嵌套結構。C#嵌套結構封送 - 對象
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ERROR_ITEM
{
byte ErrorID;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ERROR_DATA
{
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 10)]
ERROR_ITEM[] ErrorItem;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct VCP_DATA
{
[MarshalAs(UnmanagedType.Struct)]
ERROR_DATA ErrorData;
};
我需要一個字節數組複製這樣的結構,所以我嘗試以下
vcpBuffer = new VCP_DATA();
GCHandle handle = GCHandle.Alloc(vcpBuffer, GCHandleType.Pinned);
try
{
IntPtr pBuffer = handle.AddrOfPinnedObject();
Marshal.Copy(bytarray, 0, pBuffer, length);
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
但是GCHandle.Alloc()返回錯誤「類型System.Argument.Execption的未處理的異常「發生在mscorlib.dll中。 附加信息:對象包含非原始數據或不可接受數據。
感謝您的建議。我相信他們會工作,但我發現了另一種做我需要的方式。 vcpBuffer = new VCP_DATA(); GCHandle handle = GCHandle.Alloc(bytearray,GCHandleType.Pinned); \t try IntPtr pBuffer = handle.AddrOfPinnedObject(); vcpBuffer =(VCP_DATA)Marshal.PtrToStructure(pBuffer,typeof(VCP_DATA)); } finally { if(handle.IsAllocated) handle.Free(); } – Hassan
@Hassan - 你應該做出答案並接受它!這樣做是合理的,並改善了網站。 – hoodaticus