Serialize .net objects defined in .proto file

26 views
Skip to first unread message

Martin Scholz

unread,
Mar 18, 2019, 9:55:34 AM3/18/19
to grpc.io
Is it possible to do something like this within a .proto file

message ServerInfo

{

    System.Version oFileVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

}

 Or do i have to create a message type 'Version' manually in .proto file which reflects Version?

Benjamin Krämer

unread,
Mar 19, 2019, 10:20:57 AM3/19/19
to grpc.io
You have to create a message that reflects the information from System.Version that interests you. There is no direct mapping, you can achieve something close by writing an implicit cast operator or an extension method if you don't want to do it manually and have it in many places.


Keep in mind that your protos are cross platform compatible. So string is a reference type in C# (up until 7.3) but not in ProtocolBuffers or a lot of other languages. So if you plan to do more mapping, keep in mind to use google.protobuf.StringValue instead of string, otherwise you will definetly run into NullReferenceExceptions at runtime.

server_info.proto
message FileVersion {
    int32 major
= 1;
    int32 minor = 2;
    int32 build = 3;
    int32 revision = 4;
}

message ServerInfo {
    FileVersion file_version = 1;
}

ServerInfo.cs (just make sure to use the correct namespace maching your package from ServerInfo.proto)
partial class FileVersion
{
    public static implicit operator System.Version(FileVersion v)
    {
        return new System.Version(v.Major, v.Minor, v.Build, v.Revision);
    }
public static implicit operator FileVersion(System.Version v) { return new FileVersion {
             Major = v.Major,
             Minor = v.Minor,
             Build = v.Build,
             Revision = v.Revision
        };
} }


Martin Scholz

unread,
Mar 20, 2019, 3:02:19 AM3/20/19
to grpc.io
Thx!
Reply all
Reply to author
Forward
0 new messages