Before diving into the question itself, please understand, that I am not in control of the whole food chain here - answers or comments of the "you are doing it wrong" kind won't help, as I need to develop against a given API.
Components, that communicate chunks of raw data, most often do so via buffers of type byte[]
or ArraySegment<byte>
. The latter has the big advantage of being able to allocate a big buffer once and for all, then use parts of it via the ArraySegment mechanism to reduce memory allocation, fragmentation and GC problems. Nothing new here.
This comes at a price though: A (possibly foreign, closed-source) component consuming an ArraySegment<byte>
gets a reference (and thus access) to the complete array, meaning, that if it misbehaves it has the ability to corrupt completly unrelated buffers.
Now:
- An extensive search revealed no mechanism to expose only a part of an existing array as a complete array, this SO question was the closest I got, still not usable as it is "not an array".
- Inheriting from
System.Array
is not supported. - Inheriting from
System.ArraySegment<T>
is not supported either.
My chain of questions is (answering one obsoletes the later ones):
- Is there a "tricky" way to present a self-developed wrapper as a
byte[]
to a (foreign) consumer - Or is there a "tricky" way to present a self-developed wrapper as an
ArraySegment<byte>
to a (foreign) consumer, that will not expose the complete underlying array - Alternativly, is there a way to inherit from
System.Array
, that I missed - Again alternativly: Is there a way to create a
byte[]
from an aleady allocated (and pinned) memory region, that I have missed, that will not screw up, if it is GCed
Edit:
From the comment I take, I didn't say it expressivly enough. Copying data back and forth is not a solution. It is the crutch I use right now though.