2012-09-08 103 views
1

我使用C#与protobuf的图书馆和下面的类一个.bin文件创建:如何读取C++中的.proto格式的二进制文件?

[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; } 
} 

相关的.proto文件看起来像

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; 
} 

已经通过protoc.exe解析,产生TextureAtlasSettings.pb.cc和TextureAtlasSettings.pb.h。为C++。

我想读在C++所得二进制文件,所以我尝试下面的代码

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; 
} 

上面的代码将一直触发printf的。我如何正确读取文件,以便它可能被反序列化?

+1

驾驶室您尝试使用可选,而不是必需的?此外:protobuf网有一个GetProto方法,应该abl来帮助给代表.proto架构 –

+0

设置它为可选做的伎俩,谢谢。 – user1423893

回答

1

这应该足以做到这一点:

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"); 
    } 
} 
+0

即使成员值似乎设置正确,它仍然会触发printf? – user1423893

3

你实际上显示的模型表示,到protobuf网,可选场(数为零的默认值)。因此,任何零都可能被省略,这会导致C++读取器拒绝该消息(因为.proto按需要列出它)。

要获得代表.proto:

string proto = Serializer.GetProto<YourType>(); 

或者使在C#他们 “需要”:

[ProtoMember(3, IsRequired = true)] 

(ETC)

+0

谢谢你的洞察,非常感谢。 – user1423893