■ Marshal 클래스를 사용해 객체를 직렬화/역직렬화하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
using System.Runtime.InteropServices; ... /// <summary> /// 소스 항목 /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SourceItem { /// <summary> /// 값 1 /// </summary> public int Value1; /// <summary> /// 값 2 /// </summary> public double Value2; /// <summary> /// 값 3 /// </summary> public byte Value3; } ... SourceItem sourceItem = new SourceItem(); sourceItem.Value1 = 1; sourceItem.Value2 = 2; sourceItem.Value3 = 3; byte[] sourceArray = SerializeStructureObject<SourceItem>(sourceItem); SourceItem targetItem = DeserializeStructureObject<SourceItem>(sourceArray); |
■ Marshal 클래스 : 객체 직렬화/역직렬화하기
————————————————————————————————————————
#region 구조체 객체 직렬화하기 – SerializeStructureObject<T>(sourceObject)
/// <summary>
/// 구조체 객체 직렬화하기
/// </summary>
/// <typeparam name="TStruct">구조체 타입</typeparam>
/// <param name="sourceObject">소스 객체</param>
/// <returns>직렬화 구조체 객체 바이트 배열</returns>
public byte[] SerializeStructureObject<TStruct>(TStruct sourceObject) where TStruct : struct
{
int sourceSize = Marshal.SizeOf(sourceObject);
IntPtr sourceHandle = Marshal.AllocHGlobal(sourceSize);
Marshal.StructureToPtr(sourceObject, sourceHandle, false);
byte[] targetArray = new byte[sourceSize];
Marshal.Copy(sourceHandle, targetArray, 0, sourceSize);
Marshal.FreeHGlobal(sourceHandle);
return targetArray;
}
#endregion
#region 구조체 객체 역직렬화하기 – DeserializeStructureObject<TStruct>(sourceByteArray)
/// <summary>
/// 구조체 객체 역직렬화하기
/// </summary>
/// <typeparam name="TStruct">구조체 타입</typeparam>
/// <param name="sourceByteArray">소스 바이트 배열</param>
/// <returns>역직렬화 구조체 객체</returns>
public TStruct DeserializeStructureObject<TStruct>(byte[] sourceByteArray) where TStruct : struct
{
IntPtr sourceHandle = Marshal.AllocHGlobal(sourceByteArray.Length);
Marshal.Copy(sourceByteArray, 0, sourceHandle, sourceByteArray.Length);
TStruct targetObject = (TStruct)Marshal.PtrToStructure(sourceHandle, typeof(TStruct));
Marshal.FreeHGlobal(sourceHandle);
if(Marshal.SizeOf(targetObject) != sourceByteArray.Length)
{
return default(TStruct);
}
return targetObject;
}
#endregion
—————————————————————————————————-