2011-06-18 24 views
6

我在C#STRUCT編組

unsafe public struct control 
    { 
     public int bSetComPort; 
     public int iComPortIndex; 
     public int iBaudRate; 
     public int iManufactoryID; 
     public byte btAddressOfCamera; 
     public int iCameraParam; 
     public byte PresetNum; 
     public byte PresetWaitTime; 
     public byte Group; 
     public byte AutoCruiseStatus; 
     public byte Channel; 
     public fixed byte Data[64]; 
    } 

我用將其轉換爲字節數組[]的函數下面的結構是

static byte[] structtobyte(object obj) 
    { 
     int len = Marshal.SizeOf(obj); 
     byte[] arr = new byte[len]; 
     IntPtr ptr = Marshal.AllocHGlobal(len); 
     Marshal.StructureToPtr(obj, ptr, true); 
     Marshal.Copy(ptr, arr, 0, len); 
     Marshal.FreeHGlobal(ptr); 
     return arr; 
    } 

當我編譯它給

Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed. 

可能是什麼問題? 在此先感謝!

+0

你的代碼工作正常,問題必須在別的地方,很可能你想轉換另一種類型。 – svick

+0

我正在轉換我的結構,問題是結構中的字節數組。 –

+0

不是。我試過你的代碼,它的工作方式你發佈它的方式。在visual 2010中使用 – svick

回答

-1

您報告爲編譯錯誤的錯誤實際上是運行時錯誤(ArgumentException)。如果要使用structtobytecontrol轉換爲byte[],則應該通過方法參考control而不是byte陣列(byte[])。

control ctrl = new control(); 
byte[] bytes = structtobyte(ctrl); 
+0

control cnt; structtobyte(cnt);我將它傳遞給我編輯過的cnt結構體,它充滿了數據。 –

+0

你還沒有提供堆棧跟蹤/例外位置,但你得到的異常很可能來自'Marshal.SizeOf'。異常消息清楚地表明您正在提供一個字節數組。因此我的答案。 –

3

SizeOf不適用於陣列。改爲使用array.Length * Marshal.SizeOf(elementType)

+0

就是這樣!我很久沒有問過,爲什麼它給了我結構對象的錯誤大小 - 所以原因是結構中有一個數組... + + –