-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathPbConvertor.h
More file actions
87 lines (75 loc) · 2.8 KB
/
PbConvertor.h
File metadata and controls
87 lines (75 loc) · 2.8 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#ifndef PBCONVERTOR_H
#define PBCONVERTOR_H
/**
* @file PbConvertor.h
* @brief PbConvertor is used to convert protobuf message to C struct or C struct to protobuf message.
* @author xuyp
* @date 2019.12
*/
#include <string>
#include <vector>
#include <google/protobuf/message.h>
class PbConvertor
{
public:
struct MemTree
{
char *pMem;
size_t memSize;
std::vector<MemTree> vecChild;
MemTree()
{
pMem = NULL;
memSize = 0;
}
MemTree(char *pMem, size_t memSize)
{
this->pMem = pMem;
this->memSize = memSize;
}
void release()
{
for (auto &child : vecChild)
child.release();
if (NULL != pMem)
free(pMem);
}
};
/**
* @brief convert C struct to protobuf message.
* @param pStruct pointer to C struct.
* @param pPb pointer to protobuf message.
* @return whether successful.
*/
static bool struct2Pb(const char *&pStruct, google::protobuf::Message *pPb);
/**
* @brief convert C struct to serialized protobuf message.
* @param pStruct pointer to C struct.
* @param pbTypeName protobuf message type name.
* @param pSerializedPb pointer to serialized protobuf message which must be released by user using delete [].
* @param serializedPbSize serialized protobuf message size.
* @return whether successful.
*/
static bool struct2serializedPb(const char *pStruct, const std::string &pbTypeName, char *&pSerializedPb, size_t &serializedPbSize);
/**
* @brief convert protobuf message to C struct.
* @param pPb pointer to protobuf message.
* @param stru memory tree related to C struct, and pointer to C struct equals to stru.pMem.
* Memory tree must be released by user using stru.release().
* @return whether successful.
*/
static bool pb2struct(const google::protobuf::Message *pPb, MemTree &stru);
/**
* @brief convert serialized protobuf message to C struct.
* @param pbTypeName protobuf message type name.
* @param pSerializedPb pointer to serialized protobuf message.
* @param serializedPbSize serialized protobuf message size.
* @param stru memory tree related to C struct, and pointer to C struct equals to stru.pMem.
* Memory tree must be released by user using stru.release().
* @return whether successful.
*/
static bool serializedPb2struct(const std::string &pbTypeName, const char *pSerializedPb, const size_t serializedPbSize, MemTree &stru);
private:
static bool getSize(const google::protobuf::Reflection *pReflection, const google::protobuf::Message *pPb, const google::protobuf::FieldDescriptor *pFieldDescriptor, size_t &size);
};
#endif // PBCONVERTOR_H