2012-08-12 2 views
0

저는 메모리 버퍼에 직렬화하고자하는 객체가 있습니다.이 객체는 UART를 통해 임베디드 디바이스로 전송됩니다. Windows의 C# 환경에서 작업하고 있습니다.고도로 맞춤화 된 직렬화

는 내가 뭘하려는 것은 다음과 같이 두 개의 클래스를 생성하는 것입니다 :

class StatusElement 
{ 
    byte statusPart1; 
    byte statusPart2; 
} 

class DeviceCommand 
{ 
    byte Address; 
    byte Length; 
    StatusElement[] statusElements; // Can have an arbitrary number of elements in it 
} 

가 나는 직렬화, C#을 직렬화를 기반으로 바람직하게 무언가를 사용하고 싶습니다을에 두 번째 클래스를 변환하는 바이트 스트림

문제는 임베디드 장치가 정확한 시퀀스 (AddressByte, LengthByte .... ErrorCorrectionByte)를 허용하도록 하드 코딩되어 있으므로 스트림에 직렬화 메타 데이터를 추가하는 일반 C# 직렬화를 사용할 수 없다는 것입니다. 이것은 또한 Protobuf와 같은 다른 직렬화를 배제합니다.

내 질문은 : 필요한 출력을 얻기 위해 C# serialization을 사용자 정의 할 수 있습니까? 방법?

--- 업데이트 --- 도움을

감사합니다 여러분. 고려 사항 나는 반사 및 per-type 처리기를 사용하여 자체 미니 직렬기를 구현하기로 결정했습니다. 더 복잡하지만 더 많은 유연성과 자동화 기능을 제공합니다.

+1

직접 작성해야합니다. –

+0

예, 클래스를 적합한 바이트 스트림으로 직렬화하는 데 사용할 수있는 사용자 지정 논리를 작성하십시오. –

+0

[protobuf-csharp-port] (http://code.google.com/p/protobuf-csharp-port/) –

답변

1

MemoryStream을 사용하여 개체를 전체적으로 직렬화하십시오. 직렬화 복원 마찬가지로

private byte[] Serialize() 
{ 
    using (var ms = new MemoryStream()) 
    { 
     ms.WriteByte(Address); 
     ms.WriteByte(Length); 
     foreach (var element in statusElements) 
     { 
      ms.WriteByte(element.statusPart1); 
      ms.WriteByte(element.statusPart2); 
     } 
     return ms.ToArray(); 
    } 
} 

: 당신은 바이트 또는 바이트 배열을 작성하기 만하면

private static DeviceCommand Deserialize(byte[] input) 
{ 
    DeviceCommand result = new DeviceCommand(); 
    using (var ms = new MemoryStream(input)) 
    { 
     result.Address = ms.ReadByte(); 
     result.Length = ms.ReadByte(); 

     //assuming .Length contains the number of statusElements: 
     result.statusElemetns = new StatusElement[result.Length]; 
     for (int i = 0; i < result.Length; i++) 
     { 
      result.statusElements[i] = new StatusElement(); 
      result.statusElements[i].statusPart1 = ms.ReadByte(); 
      result.statusElements[i].statusPart2 = ms.ReadByte(); 
     } 
    } 
    return result; 
} 
+0

매우 일반적인 버그. 'Deserialize'에 result.statusElements [i] = new StatusElement()'가 필요합니다. –

+0

죄송합니다, 웹 사이트에 직접 작성했습니다. 고침, 고마워. – Rotem

0

, 당신은 MemoryStream을에 직접 사용할 수 있습니다. 다른 .NET 기본 유형을 사용하려면 System.IO.BinaryWriter/BinaryReader로 스트림에 액세스하십시오. 이 클래스는 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter 에서 이진 serialization 및 deserialization에 사용됩니다.

관련 문제