需要在托管 C# 和非托管 C++ 之间发送一些数据。经过一番研究 我尝试使用 Protobuf.NET。
我不确定我是否理解 ProtoBuf 的功能...
- 在 Proto 中构建类型定义。我在 c++ 和 c# 项目中都需要这个类型定义
- 使用命令行工具“protogen.exe”从类型定义中获取.cs文件和.cpp、.h
- 将 .cs 文件复制到我的 C# 项目中,并将 .cpp、.h 文件复制到我的 C++ 解决方案中。
看来我太愚蠢了,无法解决这个问题。这是我的问题和疑问。
- 是否可以在 C# 中定义类型来生成 C++ 中的文件?
- 尝试使用命令行工具 protogen.exe 和以下文件
测试1.proto
using ProtoBuf; namespace ProtocolBuffers { [ProtoContract] class Person { [ProtoMember(1)] public int Id {get;set;} [ProtoMember(2)] public string Name { get; set; } } }
test2.proto
message Person {
required int32 id = 1;
required string name = 2;
optional string email = 3;
}
没有什么对我有用。真的什么都试过了。我将原型(prototype)文件放入 命令行目录,尝试了设置目录的每个选项。如何轻松构建它们? 第二个文件正在使用 c++ 的标准 proto 命令行工具,但 c# 也需要它。真的需要你的帮助。
最佳答案
首先,请注意 protobuf-net 只是 .NET 的一个可用实现;无论如何...
“test1.proto”不是 .proto - 它是 C#;与 protobuf-net 一起使用时,.proto 不是必需的,但在互操作场景中这是一个非常好的主意。有一个 VS2010 插件可以实现此目的,或者是 protobuf-net zip 中的 protogen
工具:
protogen -i:test2.proto -o:test2.cs
这应该生成 test2.cs
,其内容为:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from: test2.proto
namespace test2
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"Person")]
public partial class Person : global::ProtoBuf.IExtensible
{
public Person() {}
private int _id;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"id", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int id
{
get { return _id; }
set { _id = value; }
}
private string _name;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string name
{
get { return _name; }
set { _name = value; }
}
private string _email = "";
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"email", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string email
{
get { return _email; }
set { _email = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
请注意,如果您想要的话,还有其他开关,例如尝试大小写标准化(因此您会得到 Id
、Name
、Email
等),或者希望它包含额外的序列化器支持(BinaryFormatter
、DataContractSerializer
等)
关于c# - Protobuf.NET 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6771444/