본문 바로가기

코딩/C#

[C#] 구조체 마샬링

반응형

Serializable : 문자로 변환하기 위해서 선언

StructLayout(LayoutKind.Sequential) : 구조체 선언

Pack=1 : pack(데이터를 읽을 단위를 정함)

MarshalAs(UnmanagedType.ByValArray, SizeConst = 배열수)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[Serializable]
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _HMIData
{
    public _hmi_macsta hmi_macsta
}
[Serializable]
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _hmi_macsta
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1100]
    public short[] oth_sta;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 298)]
    public short[] bcdv_sta1;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 298)]
    public short[] bcdv_sta2;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst= 15)]
    public string start_time;
}
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
40
41
42
43
44
45
46
47
48
public partial class ShmDataView : Form
{
    public _HMIData HMIData;
    public int ShmStructSize;
    public byte[] HMIBuffer;
 
public ShmDataView()
    {
        InitializeComponent();
        InitHMIData();
    }
 
    private void InitHMIData()
    {
        HMIData = new _HMIData();
        ShmStructSize = Marshal.SizeOf(HMIData);
        HMIBuffer = new byte[ShmStructSize];
    HMIData = (_HMIData)RawDeSerialize(HMIBuffer, HMIData.GetType());
    }
 
 
    public byte[] RawSerialize(object ShmStruct)
    {
        IntPtr buffer = Marshal.AllocHGlobal(ShmStructSize);
        Marshal.StructureToPtr(HMIData, buffer, false);
        byte[] RawData = new byte[ShmStructSize];
        Marshal.Copy(buffer, RawData, 0, ShmStructSize);
        Marshal.FreeHGlobal(buffer);
        return RawData;
    }
 
    public object RawDeSerialize(byte[] RawData, Type ShmData)
    {
        int RawSize = Marshal.SizeOf(ShmData);
 
        //Size Over
        if (RawSize > RawData.Length)
        {
            return null;
        }
 
        IntPtr buffer = Marshal.AllocHGlobal(RawSize);
        Marshal.Copy(RawData, 0, buffer, RawSize);
        object retobj = Marshal.PtrToStructure(buffer, ShmData);
        Marshal.FreeHGlobal(buffer);
        return retobj;
    }
}

public byte[] RawSerialize(object ShmStruct) 구조체로 되어있는 내용을 byte배열로 만듬

public object RawDeSerialize(byte[] RawData, Type ShmData) byte배열로 되어있는 것을 구조체(object)로 반환

그냥 sizeof를 하면 나오지 않는다.

Marshal.SizeOf(객체) 로 해야 C언어의 sizeof(구조체)와 같은 형태가 나온다

반응형

'코딩 > C#' 카테고리의 다른 글

[C#] 문자열 마샬링  (0) 2016.03.04
[C#] 클래스와 구조체  (0) 2016.03.03
[C#] IContainer 인터페이스  (0) 2016.03.03
[C#] 마샬링(Marshalling)  (0) 2016.03.02
[C#] show / showDialog 차이점  (0) 2016.03.02