I have a .bin file created using C# with a protobuf library and the following class:
[ProtoContract]
class TextureAtlasEntry
{
[ProtoMember(1)]
public int Height { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
[ProtoMember(3)]
public int Width { get; set; }
[ProtoMember(4)]
public int X { get; set; }
[ProtoMember(5)]
public int Y { get; set; }
}
The associated .proto file looks like
package TextureAtlasSettings; // Namespace equivalent
message TextureAtlasEntry
{
required int32 Height = 1;
required string Name = 2;
required int32 Width = 3;
required int32 X = 4;
required int32 Y = 5;
}
Which has been parsed through protoc.exe to produce TextureAtlasSettings.pb.cc and TextureAtlasSettings.pb.h. for C++.
I would like to read the resultant binary file in C++, so I tried the following code
TextureAtlasSettings::TextureAtlasEntry taSettings;
ifstream::pos_type size;
char *memblock;
ifstream file("Content\\Protobuf\\TextureAtlas0.bin", ios::in | ios::binary);
if (file.is_open())
{
size = file.tellg();
memblock = new char[size];
file.seekg(0, ios::beg);
file.read(memblock, size);
file.close();
fstream input(&memblock[0], ios::in | ios::binary);
if (!taSettings.ParseFromIstream(&file))
{
printf("Failed to parse TextureAtlasEntry");
}
delete[] memblock;
}
The code above will always trigger the printf. How do I go about reading the file correctly so it may be deserialized?
The model you show actually represents, to protobuf-net, optional fields (several with a default of zero). Consequently, any zeros might be omitted, which would cause the c++ reader to reject the message (since your .proto lists it as required).
To get the representative .proto:
string proto = Serializer.GetProto<YourType>();
Or to make them "required" in the c#:
[ProtoMember(3, IsRequired = true)]
(etc)
It should be sufficient to do this:
TextureAtlasSettings::TextureAtlasEntry taSettings;
ifstream file("Content\\Protobuf\\TextureAtlas0.bin", ios::in | ios::binary);
if (file.is_open())
{
if (!taSettings.ParseFromIstream(&file))
{
printf("Failed to parse TextureAtlasEntry");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.