Skip to content

Latest commit

 

History

History
136 lines (117 loc) · 2.6 KB

序列化以及反序列化的方案.md

File metadata and controls

136 lines (117 loc) · 2.6 KB

Serialize

In C++

  • Simple serialization
class GameObject
{
public:
	char mName[32];
	int mLayer;
};
void SaveToFile(const char* path, void* buffer, int size)
{
	FILE* file;
	int err = fopen_s(&file, path, "wb");
	if (err == 0)
	{
		fwrite(buffer, sizeof(char), size, file);
		fclose(file);
	}
}
char* GetFileContent(const char* path, int& size)
{
	FILE* file;
	int err = fopen_s(&file, path, "rb");
	if (err == 0)
	{
		fseek(file, 0, SEEK_END);
		int nLen = ftell(file);
		size = nLen;
		char* szBuffer = new char[nLen + 1];
		rewind(file);
		fread(szBuffer, sizeof(char), nLen, file);
		fclose(file);
		szBuffer[nLen] = 0;
		return szBuffer;
	}
	return NULL;
}
int main(int argc, char* argv[])
{
	cout << "Test for Serialize----------" << endl;
	GameObject go;
	memset(go.mName, 0, 32);
	strcpy_s(go.mName, 32, "Yosef");
	go.mLayer = 1;

	char szBuffer[64] = { 0 };
	memcpy(szBuffer, &go, sizeof(go));
	cout << "GameObject" << endl;
	cout << go.mName << " " << go.mLayer << endl;
	SaveToFile("test.prefab", szBuffer, sizeof(go));

	int size = 0;
	char* fileContent = GetFileContent("test.prefab", size);
	BB a;
	memcpy(&a, fileContent, sizeof(BB));
	cout << "BB" << endl;
	cout << a.mName << " " << a.mLayer << endl;
	delete[]fileContent;
	system("pause");
	return 0;
}
  • proto buffer

    package XiaoHua;
    option optimize_for=LITE_RUNTIME;
    message Prefab{
    	optional string name=1;
    	optional int32 layer=2;
    }
cout << "Proto buffer-----------" << endl;
	GameObject aa;
	memset(aa.mName, 0, 32);
	strcpy_s(aa.mName, 32, "Yoseffffff");
	aa.mLayer = 2;
	XiaoHua::Prefab prefab;
	prefab.set_name(aa.mName);
	prefab.set_layer(aa.mLayer);
	char szBuffer[128] = { 0 };
	prefab.SerializeToArray(szBuffer, 128);

	int size1 = 0;
	char* fileco = GetFileContent("test1.prefab", size);
	prefab.ParseFromArray(fileco, size);
	cout << prefab.name() << " " << prefab.layer() << endl;
protobuf c++
bool bool
double double
float float
int32 int
uint32 unsigned int
int64 _int64
string std::string
bytes std::string
enum enum
message object of class
  • How to use Protobuf
//命名空间
package namespace;
//optional , required, repeated
// 修饰符, 类型, 变量名, tag(位置)
message Prefab{
	optional int32 layer=1;
	required int32 mask=2;
	repeated int32 haha=3; //设置数组
	//required 必须设定值, optional, repeated 非必须
}