Reputation: 2263
I'm trying to generate a Bson from Json. I tried using Json.Net but there seems to be a documented behavior where the library produces uint64 for integer fields. unfortunately we must use uint32.
Hence I'm trying to use mongodb bson library. but I can't figure how to convert a BsonDocument into a BsonBinaryData.
//Works well, I can inspect with watch
MongoDB.Bson.BsonDocument doc = MongoDB.Bson.BsonDocument.Parse(json);
//Invalid cast exception
byte[] data = doc.AsByteArray;
Upvotes: 4
Views: 2950
Reputation: 1596
To get the raw byte array representation of a BsonDocument
instance, use the extension method ToBson()
. To create a BsonDocument
from the byte array representation, create an instance of RawBsonDocument
, which is derived from BsonDocument
and takes a byte array as constructor argument.
Here is an example for using two bson documents to pass parameters to a native c function call and retrieve the result:
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);
}
Note that the memory p
points to must somehow be freed.
Upvotes: 2