C# 如何在C+;中读取.proto格式的二进制文件+;?
我使用C#创建了一个.bin文件,其中包含protobuf库和以下类:C# 如何在C+;中读取.proto格式的二进制文件+;?,c#,c++,protocol-buffers,C#,C++,Protocol Buffers,我使用C#创建了一个.bin文件,其中包含protobuf库和以下类: [ProtoContract] class TextureAtlasEntry { [ProtoMember(1)] public int Height { get; set; } [ProtoMember(2)] public string Name { get; set; } [ProtoMember(3)] public int Width { get; set; }
[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对其进行解析,以生成TextureAtlassetings.pb.cc和TextureAtlassetings.pb.h。对于C++,
我想读取C++中的结果二进制文件,所以我尝试了下面的代码< /p>
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。如何正确读取该文件,以便将其反序列化 这样做就足够了:
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");
}
}
这样做就足够了:
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");
}
}
对于protobuf net,您显示的模型实际上表示可选字段(一些字段的默认值为零)。因此,任何零可能被省略,这将导致C++读者拒绝消息(因为您的.PROTO按需要列出它)。 要获取代表,请执行以下操作:
string proto = Serializer.GetProto<YourType>();
(etc)对于protobuf net,您显示的模型实际上表示可选字段(一些字段默认为零)。因此,任何零可能被省略,这将导致C++读者拒绝消息(因为您的.PROTO按需要列出它)。 要获取代表,请执行以下操作:
string proto = Serializer.GetProto<YourType>();
(etc)即使成员值设置正确,仍会触发printf?!即使成员值设置正确,仍会触发printf?!您是否尝试使用可选的而不是必需的?另外:protobuf net有一个GetProto方法,应该是abl,以帮助代表。proto schema将其设置为optional就可以了,谢谢。您是否尝试使用optional而不是required?另外:protobuf net有一个GetProto方法,应该是abl的,以帮助向代表提供帮助。proto SchemaSet将其设置为optional会起到作用,谢谢。感谢您的见解,非常感谢。感谢您的见解,非常感谢。