c 序列化(緊密型資料結構)(一)

2021-09-26 20:03:58 字數 2469 閱讀 6063

c#自帶各種方便的序列化功能,例如可以序列化類為json,序列化為xml。

我對c#了解甚少,最近需要做乙個unity3d伺服器和c++客戶端網路通訊的功能,所以實現了乙個簡略序列化函式,搓作留此紀念。

實現如下:

首先實現乙個動態快取區,可以自動增大,具有增加資料和獲取資料介面,用於進行序列化時使用

該類使用泛型實現

dynamical.cs

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading.tasks;

namespace network.network

public int getsize()

public void reset()

public void adddata(t data, int size)

else

}cur_len += size;

max_len += buff.count;

}public void removedata(int start, int size)

for (int i = 0; i < cur_len - start - size; i++)

cur_len -= size;

}void getdata(ref t data, int start, int size)

t tmp = new t[size];

for (int i = 0; i < size; i ++)

data = tmp;

}listbuff;

int cur_len;

int max_len;

}}

1、首先實現乙個基類,有兩個虛函式,serializable()、deserializable()需要子類去實現

2、再實現乙個通用的serializablebase()、deserializablebase()函式,可以序列化反序列化基本型別

當然可以在這個兩個函式中增加其他非基本型別的序列化,反序列化,那麼子類就只需要不斷遞迴呼叫serializable,

serializablebase就可以實現序列化。deserializable,deserializablebase實現反序列化對複雜型別也手到擒來。

serialization.cs

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading.tasks;

namespace network.network

public virtual void deserializable(ref byte buff, ref int offset, int size)

public void serializablebase(ref dynamicalbuff, object obj)

else if (obj is int)

else if (obj is float)

else if (obj is double)

else if (obj is char)

}public object deserializablebase(type type, ref byte buff, ref int offset, int size)

else if (type == typeof(int))

else if (type == typeof(double))

else if (type == typeof(float))

else if (type == typeof(char))

return obj; }}

public class listnode : serialization

public override void deserializable(ref byte buff, ref int offset, int size)

}public class childclass : serialization

}public override void deserializable(ref byte buff, ref int offset, int size)}}

}

test.cs

private void form1_load(object sender, eventargs e)

二、缺點

每個子類都要實現deserializable,serializable 函式,容易出錯,編碼也不方便。比起原生的json,xml序列化。不過傳輸過程中占用的消耗小,適用於網路傳輸。

C 序列化結構體

在將物件或結構體序列化成二進位制資料流時,我們通常都會使用 system.runtime.serialization.formatters.binary.binaryformatter 類來實現,但是這種方式會把物件或結構體的型別資訊給序列化到資料流中,在做通迅時,這種方式是不可取的.在c c 中,...

資料結構 二叉樹的序列化 反序列化

前序遍歷 中序遍歷 後序遍歷 層序遍歷 include include include include using namespace std class node 1 前序遍歷 序列化 void front seq node root,queue q string s to string root...

利用yaml cpp庫對資料結構序列化

有時候我們要將乙個int float bool轉成字串,這個用boost能簡單地實現,但是一些複雜的資料結構比如stl的vector map list set甚至是組合的vector map 資料結構,可以通過yaml庫來實現序列化成字串,下面簡單地實現vector的序列化和反序列化,可以看出是支援...