[英]Generate C# from proto files and vice versa interpreting custom options
I'm using protobuf-net , and I'm trying to: 我正在使用protobuf-net ,我正在尝试:
That's pretty easy using respectively: 这分别很容易使用:
protogen.exe
tool protogen.exe
工具 Serializer<T>.GetProto()
method Serializer<T>.GetProto()
方法 But the thing is that I need to support protobuffer custom options and it doesn't seem to be as straightforward as I though. 但问题是我需要支持protobuffer 自定义选项 ,但它似乎并不像我那样简单。
Let me explain: 让我解释:
Basically, given: 基本上,给出:
message person {
option (my_message_option) = true;
optional string firstname = 1 [(my_field_option) = 42];
optional string lastname = 2 [(my_field_option) = 12];
optional int age = 3;
}
I want to generate: 我想生成:
[ProtoContract, MyMessageOption(true)]
public class Person
{
[ProtoMember(1), MyFieldOption(42)]
public string Firstname;
[ProtoMember(2), MyFieldOption(12)]
public string Firstname;
[ProtoMember(3)]
public string Firstname;
}
...and vice versa. ......反之亦然。
Notes : 备注:
my_message_option
and my_field_option
) can already exist in a protofile (say, my_custom_options.proto), and the custom attributes classes can also exist somewhere ( MyMessageOptionAttribute
and MyFieldOptionAttribute
). 自定义选项定义( my_message_option
和my_field_option
)已经存在于protofile中(例如,my_custom_options.proto),自定义属性类也可以存在于某个位置( MyMessageOptionAttribute
和MyFieldOptionAttribute
)。 What's the preferred way to achieve that? 实现这一目标的首选方式是什么? The solution doesn't have to rely on protobuf-net. 解决方案不必依赖protobuf-net。
I ended up by forking ProtoGen project from protobuf-csharp to make public some internal types (generators, for the most part) and to make the SourceGenerators
extensible by allowing custom generator registrations. 我最后通过从protobuf-csharp分配ProtoGen项目来公开一些内部类型(生成器,大部分),并通过允许自定义生成器注册使SourceGenerators
可扩展。
This way, I was able to use the proto descriptor object model to write my own C# generator. 这样,我就可以使用proto描述符对象模型来编写自己的C#生成器。
One tricky point is to register your custom options types before launching the parsing : 一个棘手的问题是在启动解析之前注册自定义选项类型:
Protoc.exe
then ProtoGen.exe
) 生成与您的自定义选项对应的C#类型(使用Protoc.exe
然后是ProtoGen.exe
) ExtensionRegistry
by using the generated RegisterAllExtensions
methods. 使用生成的RegisterAllExtensions
方法配置ExtensionRegistry
。 Descriptor.Options
collection. 在每个生成器中,您可以访问上下文Descriptor.Options
集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.