gpt4 book ai didi

.net - 无法将类型为 'MongoDB.Bson.BsonDocument' 的对象转换为类型 'MongoDB.Bson.BsonBinaryData'

转载 作者:可可西里 更新时间:2023-11-01 09:14:06 33 4
gpt4 key购买 nike

我正在尝试从 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com