2

Is it possible with flatbuffers in C# to serialize objects to native (unmanaged) memory buffer? So I want to do these steps:

  1. Allocate a native memory buffer from native memory
  2. Create objects in C# and serialize them into the allocated buffer
  3. Send this memory buffer to C++ for deserialization

I'm thinking either of some custom memory buffer allocator in C#, or of some way of transferring ownership of a memory buffer form C# to C++.

In general I want to avoid copying memory when sending data from C# to C++ and vice versa. I want this memory buffer to be shared between C# and C++.

How do I do that?

Max
  • 19,654
  • 13
  • 84
  • 122
  • 1
    Can anybody explain downvotes and close votes? – Max Jul 07 '17 at 22:16
  • you can pin c# memory and pass its address to a C function https://stackoverflow.com/questions/5143349/c-sharp-how-can-i-pin-an-object-in-memory-without-marshalling-the-object and here https://manski.net/2012/06/pinvoke-tutorial-pinning-part-4/ – pm100 Jul 07 '17 at 22:36

2 Answers2

1

No, the current FlatBuffers implementation is hard-coded to write to a regular byte array. You could copy this array to native memory afterwards, or like @pm100 says, pin it.

All serialization in FlatBuffers goes through an abstraction called the ByteBuffer, so if you made an implementation of that for native memory, it could be used directly relatively easily.

Aardappel
  • 5,559
  • 1
  • 19
  • 22
  • It looks like it would not be possible without changes in the flatbuffers library itself, since nothing in ByteBuffer is even virtual. It's not clear where it would be possible to inject a custom implementation. – Ran Sep 10 '19 at 00:01
0

Yes, if you use C++/CLI. Basic data types such as bool, 32-bit int, short, etc are same. For other types check it out msclr::interop::marshal_as<>.

Similar post: C++/CLI Converting from System::String^ to std::string

JazzSoft
  • 392
  • 2
  • 11
  • Thanks, but this is not what I'm asking. My question is about using flatbuffers library and about normal C++. And marshaling does do memory copy, which is exactly the thing I want to avoid. – Max Jul 07 '17 at 22:12