下載protobuf
下載地址:https://github.com/google/protobuf/releases
選擇protoc-xxx-win32.zip下載
配置環境變量
將解壓出來的protoc.exe放在一全英文路徑下,並把其路徑名放在windows環境變量下的path下。
用";" 半角分號隔開
生成代碼
在所使用的proto文件路徑下打開cmd窗口執行以下命令:
protoc -I=源地址 --csharp_out=目標地址 xxx.proto
此處生成時會以 proto 里面注明的csharp_package為路徑完整生成,所以目標地址不必包含csharp_package及之后的路徑,比如:option csharp_package = "com.test.protocol";,那么就會生成com/test/protocol/XXX.cs
參數解釋:
-I:主要用於指定待編譯的 .proto 消息定義文件所在的目錄,即可能出現的包含文件的路徑。此處指定的路徑不能為空,如果是當前目錄,直接使用.,如果是子目錄,直接使用子目錄相對徑,如:file1/file2/file3,如果要編譯的文件指定的文件路徑為file3/test.proto,那么應這么寫-I=file1/file2,而不要一直寫到file3。
示例
使用的文件:
Test.proto(在 D:\test_protoc 下)
syntax = "proto3"; package GrpcLibrary; service GrpcService { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
生成:
C:\Users\admin>protoc -I=D:\test_protoc --csharp_out=D:\test_protoc Test.proto
生成后: