2010-09-15 33 views
4

J'ai un tableau d'octets que je veux réinterpréter comme un tableau de structures blittables, idéalement sans copier. L'utilisation de code dangereux est très bien. Je connais le nombre d'octets et le nombre de structures que je veux sortir à la fin.Ré-interpréter un tableau d'octets sous la forme d'un tableau de structures

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

Je crois que vous pouvez trouver votre réponse à http://stackoverflow.com/questions/621493/c-unsafe-value-type- array-to-byte-array-conversions qui contient des techniques de conversion qui fonctionnent dans votre cas. – sisve

Répondre

4

Essayez ceci. Je l'ai testé et il fonctionne:

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; 
    } 

Utilisation:

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

Cela utilise la copie, non? –

+0

@SargeBorsch oui. La première boucle est la copie dans le nouveau tampon. Est-ce un problème? – Aliostad