Pergunta

Qual seria a melhor maneira de preencher uma estrutura C# a partir de uma matriz de bytes[] onde os dados eram de uma estrutura C/C++?A estrutura C seria mais ou menos assim (meu C está muito enferrujado):

typedef OldStuff {
    CHAR Name[8];
    UInt32 User;
    CHAR Location[8];
    UInt32 TimeStamp;
    UInt32 Sequence;
    CHAR Tracking[16];
    CHAR Filler[12];
}

E preencheria algo assim:

[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
    [FieldOffset(0)]
    public string Name;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(8)]
    public uint User;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
    [FieldOffset(12)]
    public string Location;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(20)]
    public uint TimeStamp;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(24)]
    public uint Sequence;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    [FieldOffset(28)]
    public string Tracking;
}

Qual é a melhor maneira de copiar OldStuff para NewStuff, se OldStuff foi passado como array de bytes[]?

Atualmente estou fazendo algo parecido com o seguinte, mas parece meio desajeitado.

GCHandle handle;
NewStuff MyStuff;

int BufferSize = Marshal.SizeOf(typeof(NewStuff));
byte[] buff = new byte[BufferSize];

Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);

handle = GCHandle.Alloc(buff, GCHandleType.Pinned);

MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));

handle.Free();

Existe melhor maneira de conseguir isso?


Usaria o BinaryReader classe oferece quaisquer ganhos de desempenho em relação à fixação da memória e ao uso Marshal.PtrStructure?

Foi útil?

Solução

Pelo que posso ver nesse contexto, você não precisa copiar SomeByteArray em um buffer.Você simplesmente precisa obter o controle de SomeByteArray, fixe-o, copie o IntPtr dados usando PtrToStructure e depois solte.Não há necessidade de uma cópia.

Isso seria:

NewStuff ByteArrayToNewStuff(byte[] bytes)
{
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try
    {
        NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));
    }
    finally
    {
        handle.Free();
    }
    return stuff;
}

Versão genérica:

T ByteArrayToStructure<T>(byte[] bytes) where T: struct 
{
    T stuff;
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try
    {
        stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    }
    finally
    {
        handle.Free();
    }
    return stuff;
}

Versão mais simples (requer unsafe trocar):

unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
    fixed (byte* ptr = &bytes[0])
    {
        return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T));
    }
}

Outras dicas

Aqui está uma versão segura de exceção do resposta aceita:

public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
    var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try {
        return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    }
    finally {
        handle.Free();
    }
}

Cuidado com problemas de embalagem.No exemplo que você deu, todos os campos estão com deslocamentos óbvios porque tudo está nos limites de 4 bytes, mas nem sempre será esse o caso.O Visual C++ é empacotado em limites de 8 bytes por padrão.

object ByteArrayToStructure(byte[] bytearray, object structureObj, int position)
{
    int length = Marshal.SizeOf(structureObj);
    IntPtr ptr = Marshal.AllocHGlobal(length);
    Marshal.Copy(bytearray, 0, ptr, length);
    structureObj = Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(bytearray, position), structureObj.GetType());
    Marshal.FreeHGlobal(ptr);
    return structureObj;
}   

Tenha isso

Se você tiver um byte[], poderá usar a classe BinaryReader e definir valores em NewStuff usando os métodos ReadX disponíveis.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top