我正在尝试从 Json 生成 Bson。我尝试使用 Json.Net,但似乎有记录的行为,其中库为整数字段生成 uint64。不幸的是,我们必须使用 uint32。
因此我正在尝试使用 mongodb bson 库。但我不知道如何将 BsonDocument 转换为 BsonBinaryData。
//Works well, I can inspect with watch
MongoDB.Bson.BsonDocument doc = MongoDB.Bson.BsonDocument.Parse(json);
//Invalid cast exception
byte[] data = doc.AsByteArray;
最佳答案
要获取 BsonDocument
实例的原始字节数组表示,请使用扩展方法 ToBson()
.要从字节数组表示形式创建一个 BsonDocument
,请创建一个 RawBsonDocument
的实例,它派生自 BsonDocument
并将字节数组作为构造函数参数.
下面是一个使用两个 bson 文档将参数传递给原生 c 函数调用并检索结果的示例:
public static BsonDocument CallCFunction(BsonDocument doc) {
byte[] input = doc.ToBson();
int length = input.Length;
IntPtr p = DllImportClass.CFunction(ref length, input);
if (p == IntPtr.Zero) {
// handle error
}
// the value of length is changed in the c function
var output = new byte[length];
System.Runtime.InteropServices.Marshal.Copy(p, output, 0, length);
return new RawBsonDocument(output);
}
请注意,p
指向的内存必须以某种方式释放。
关于.net - 无法将类型为 'MongoDB.Bson.BsonDocument' 的对象转换为类型 'MongoDB.Bson.BsonBinaryData',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38569317/