2010-09-15 101 views
4

我有一個字節數組,我想將它重新解釋爲一個可變結構數組,理想情況下不需要複製。使用不安全的代碼很好。我知道字節的數量,以及我最終想要獲得的結構數量。將字節數組重新解釋爲一個結構數組

public struct MyStruct 
{ 
    public uint val1; 
    public uint val2; 
    // yadda yadda yadda.... 
} 


byte[] structBytes = reader.ReadBytes(byteNum); 
MyStruct[] structs; 

fixed (byte* bytes = structBytes) 
{ 
    structs = // .. what goes here? 

    // the following doesn't work, presumably because 
    // it doesnt know how many MyStructs there are...: 
    // structs = (MyStruct[])bytes; 
} 
+0

我相信你可以在http://stackoverflow.com/questions/621493/c-unsafe-value-type-找到答案包含轉換技術的數組到字節數組轉換,這些轉換技術適用於您的情況。 – sisve 2010-09-15 11:38:35

回答

4

試試這個。我已經測試和它的工作原理:

struct MyStruct 
    { 
     public int i1; 
     public int i2; 
    } 

    private static unsafe MyStruct[] GetMyStruct(Byte[] buffer) 
    { 
     int count = buffer.Length/sizeof(MyStruct); 
     MyStruct[] result = new MyStruct[count]; 
     MyStruct* ptr; 

     fixed (byte* localBytes = new byte[buffer.Length]) 
     { 
      for (int i = 0; i < buffer.Length; i++) 
      { 
       localBytes[i] = buffer[i]; 
      } 
      for (int i = 0; i < count; i++) 
      { 
       ptr = (MyStruct*) (localBytes + sizeof (MyStruct)*i); 
       result[i] = new MyStruct(); 
       result[i] = *ptr; 
      } 
     } 


     return result; 
    } 

用法:

 byte[] bb = new byte[] { 0,0,0,1 ,1,0,0,0 }; 
     MyStruct[] structs = GetMyStruct(bb); // i1=1 and i2=16777216 
+0

這使用複製,對吧? – 2013-07-04 05:23:54

+0

@SargeBorsch是的。首先for循環是複製到新的緩衝區。那是問題嗎? – Aliostad 2013-07-04 07:52:05

相關問題