Click or drag to resize

JCOBridgeStreamT Class

An UnmanagedMemoryStream that provides direct .NET stream access to the native memory of a JVM array obtained from ToStreamT(FileAccess, Boolean).
Inheritance Hierarchy
SystemObject
  SystemMarshalByRefObject
    System.IOStream
      System.IOUnmanagedMemoryStream
        MASES.JCOBridge.C2JBridgeJCOBridgeStreamT

Namespace: MASES.JCOBridge.C2JBridge
Assembly: C2JBridge (in C2JBridge.dll) Version: 2.6.9.260611-9a148513a79c26cdd7f1dde468f4f9e06ef3bc7e
Syntax
public class JCOBridgeStream<T> : UnmanagedMemoryStream, 
	IEnumerable<T>, IEnumerable
where T : struct, new()

Type Parameters

T
The .NET primitive type corresponding to the element type of this IJavaArray. Supported types reflect the JVM primitive type system:
JVM type.NET type
booleanbool
bytebyte
shortshort
intint
longlong
floatfloat
doubledouble
charchar
Unsigned types (sbyte, ushort, uint, ulong) are not supported as they have no equivalent in the JVM type system. Passing an unsupported type throws NotSupportedException at runtime; passing a type inconsistent with the actual JVM array element type throws InvalidOperationException.

The JCOBridgeStreamT type exposes the following members.

Properties
 NameDescription
Public propertyCanReadGets a value indicating whether a stream supports reading.
(Inherited from UnmanagedMemoryStream)
Public propertyCanSeekGets a value indicating whether a stream supports seeking.
(Inherited from UnmanagedMemoryStream)
Public propertyCanTimeoutGets a value that determines whether the current stream can time out.
(Inherited from Stream)
Public propertyCanWriteGets a value indicating whether a stream supports writing.
(Inherited from UnmanagedMemoryStream)
Public propertyCapacityGets the stream length (size) or the total amount of memory assigned to a stream (capacity).
(Inherited from UnmanagedMemoryStream)
Public propertyCount Gets the number of elements of type T in the stream.
Public propertyItem Gets or sets the element at the specified index.
Public propertyLengthGets the length of the data in a stream.
(Inherited from UnmanagedMemoryStream)
Public propertyPositionGets or sets the current position in a stream.
(Inherited from UnmanagedMemoryStream)
Public propertyPositionPointerGets or sets a byte pointer to a stream based on the current position in the stream.
(Inherited from UnmanagedMemoryStream)
Public propertyReadTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to read before timing out.
(Inherited from Stream)
Public propertyWriteTimeoutGets or sets a value, in miliseconds, that determines how long the stream will attempt to write before timing out.
(Inherited from Stream)
Top
Methods
 NameDescription
Public methodAsSpan Returns a zero-copy ReadOnlySpanT over the entire stream contents, starting at offset zero regardless of the current Position.

Prefer this over IEnumerableT for bulk comparisons and copies: MemoryExtensions.SequenceEqual{T}(ReadOnlySpan{T}, ReadOnlySpan{T}) dispatches to SIMD hardware intrinsics with no allocations.

Public methodAsSpanFromPosition Returns a zero-copy ReadOnlySpanT over the stream contents starting at the current Position.
Public methodAsWritableSpan Returns a zero-copy writable SpanT over the entire buffer, starting at offset zero regardless of the current position.

Contract: if any element is modified through the returned span, FlushOnDispose MUST be called before Dispose(Boolean) to ensure changes are written back. Failing to do so results in silent data loss. For single or sparse writes prefer Write(...), which sets the flush flag automatically.

Public methodAsWritableSpanFromPosition Returns a zero-copy writable SpanT over the buffer starting at the specified element index.

Contract: if any element is modified through the returned span, FlushOnDispose MUST be called before Dispose(Boolean) to ensure changes are written back. Failing to do so results in silent data loss. For single or sparse writes prefer Write(...), which sets the flush flag automatically.

Public methodBeginReadBegins an asynchronous read operation. (Consider using ReadAsync(Byte, Int32, Int32) instead; see the Remarks section.)
(Inherited from Stream)
Public methodBeginWriteBegins an asynchronous write operation. (Consider using WriteAsync(Byte, Int32, Int32) instead; see the Remarks section.)
(Inherited from Stream)
Public methodCloseCloses the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed.
(Inherited from Stream)
Public methodCopyTo(Stream)Reads the bytes from the current stream and writes them to another stream.
(Inherited from Stream)
Public methodCopyTo(T, Int32) Copies all elements into destination starting at destinationIndex.

On .NET 5+ and .NET Standard 2.1 this operation is backed by ReadOnlySpanT and dispatches to SIMD hardware intrinsics with no intermediate allocation. On .NET Framework the copy is performed via MemoryCopy(Void*, Void*, Int64, Int64), which uses the OS-level memcpy implementation and is SIMD-accelerated on all supported platforms without requiring any additional dependency. In both cases no intermediate managed allocation occurs.

Public methodCopyTo(Stream, Int32)Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.
(Inherited from Stream)
Public methodCopyToAsync(Stream)Asynchronously reads the bytes from the current stream and writes them to another stream.
(Inherited from Stream)
Public methodCopyToAsync(Stream, Int32)Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.
(Inherited from Stream)
Public methodCopyToAsync(Stream, Int32, CancellationToken)Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.
(Inherited from Stream)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Protected methodCreateWaitHandleAllocates a WaitHandle object.
(Inherited from Stream)
Obsolete
Public methodDisposeReleases all resources used by the Stream.
(Inherited from Stream)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the UnmanagedMemoryStream and optionally releases the managed resources.
(Overrides UnmanagedMemoryStreamDispose(Boolean))
Public methodEndReadWaits for the pending asynchronous read to complete. (Consider using ReadAsync(Byte, Int32, Int32) instead; see the Remarks section.)
(Inherited from Stream)
Public methodEndWriteEnds an asynchronous write operation. (Consider using WriteAsync(Byte, Int32, Int32) instead; see the Remarks section.)
(Inherited from Stream)
Public methodEqualsDetermines whether the specified object is equal to the current object.
(Inherited from Object)
Protected methodFinalize Finalizer
(Overrides ObjectFinalize)
Public methodFlushOverrides the Flush method so that no action is performed.
(Inherited from UnmanagedMemoryStream)
Public methodFlushAsyncAsynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.
(Inherited from Stream)
Public methodFlushAsync(CancellationToken)Overrides the FlushAsync(CancellationToken) method so that the operation is cancelled if specified, but no other action is performed.Available starting in .NET Framework 4.6
(Inherited from UnmanagedMemoryStream)
Public methodFlushOnDispose Marks this stream to flush all native memory changes back to the underlying resource on Dispose(Boolean).

Must be called after any direct write performed through AsWritableSpan or AsWritableSpanFromPosition before the stream is closed.

This method is idempotent — calling it multiple times has no additional effect.

Public methodGetEnumeratorReturns an enumerator that iterates through the collection.
Public methodGetHashCodeServes as the default hash function.
(Inherited from Object)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Public methodGetTypeGets the Type of the current instance.
(Inherited from Object)
Protected methodInitialize(Byte*, Int64, Int64, FileAccess)Initializes a new instance of the UnmanagedMemoryStream class by using a pointer to an unmanaged memory location.
(Inherited from UnmanagedMemoryStream)
Protected methodInitialize(SafeBuffer, Int64, Int64, FileAccess)Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset, length, and file access.
(Inherited from UnmanagedMemoryStream)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object.
(Inherited from Object)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Protected methodObjectInvariantProvides support for a Contract.
(Inherited from Stream)
Obsolete
Public methodReadReads the specified number of bytes into the specified array.
(Inherited from UnmanagedMemoryStream)
Public methodReadAsync(Byte, Int32, Int32)Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
(Inherited from Stream)
Public methodReadAsync(Byte, Int32, Int32, CancellationToken)Asynchronously reads the specified number of bytes into the specified array.Available starting in .NET Framework 4.6
(Inherited from UnmanagedMemoryStream)
Public methodReadByteReads a byte from a stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
(Inherited from UnmanagedMemoryStream)
Public methodSeekSets the current position of the current stream to the given value.
(Inherited from UnmanagedMemoryStream)
Public methodSetLengthSets the length of a stream to a specified value.
(Inherited from UnmanagedMemoryStream)
Public methodToStringReturns a string that represents the current object.
(Inherited from Object)
Public methodWriteWrites a block of bytes to the current stream using data from a buffer.
(Overrides UnmanagedMemoryStreamWrite(Byte, Int32, Int32))
Public methodWriteAsync(Byte, Int32, Int32)Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
(Inherited from Stream)
Public methodWriteAsync(Byte, Int32, Int32, CancellationToken)Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.Available starting in .NET Framework 4.6
(Overrides UnmanagedMemoryStreamWriteAsync(Byte, Int32, Int32, CancellationToken))
Public methodWriteByteWrites a byte to the current position in the file stream.
(Overrides UnmanagedMemoryStreamWriteByte(Byte))
Top
Extension Methods
 NameDescription
Public Extension MethodConvertTReturn Converts a generic object
(Defined by JCOBridgeExtensions)
Public Extension MethodToNative Converts a generic input to an object manageable from the JVM
(Defined by JCOBridgeExtensions)
Top
Explicit Interface Implementations
 NameDescription
Explicit interface implementationPrivate methodIEnumerableGetEnumeratorReturns an enumerator that iterates through a collection.
Top
Remarks

Instances of this class must be obtained through ToStreamT(FileAccess, Boolean); direct instantiation is not supported.

Standard license. The stream operates on a local copy of the JVM array data, consistent with the snapshot already available from ToArray. There are no constraints on JVM interaction or stream lifetime. When opened with write access, any modifications are written back to the JVM array automatically on Dispose. If Dispose is not called explicitly, the finalizer ensures cleanup without adverse effects, though explicit disposal is always preferred.

HPA license — standard access (forceRawMemory = false). The JVM runtime may expose a direct pointer or an internal copy depending on its implementation; in both cases the GC runs freely and JVM interaction is unrestricted. Dispose should be called promptly to release the JVM resource; relying on the finalizer is discouraged as it keeps the resource held for an indeterminate time.

HPA license — raw memory access (forceRawMemory = true). The JVM garbage collector is suspended for the entire lifetime of this stream. No JVM interaction of any kind is permitted while the stream is alive (no object allocation, no method calls, no blocking operations). Dispose is mandatory, must be invoked immediately after the memory operation completes, and must not be left to the finalizer. Violating these constraints may result in a deadlock or a JVM crash. Always use a using block.

Performance characteristics. Per-element access through ItemInt32 or IEnumerableT on JVM-resident memory is inherently slower than equivalent access on a managed .NET array. The JVM heap and the CLR managed heap occupy separate physical memory regions; each element access risks a TLB miss or CPU cache miss because the hardware prefetcher has no prior knowledge of those pages. A managed array, by contrast, is warm in the CPU cache immediately after any copy and benefits from hardware prefetching and JIT optimisations on subsequent accesses.

This class is therefore most appropriate when the buffer is large enough that copying it into managed memory would be prohibitively expensive in time or space (typically hundreds of MB or more), and the access pattern is sparse or random so that only a small fraction of elements are actually read or written. When the entire buffer must be scanned or compared, prefer AsSpan combined with MemoryExtensions.SequenceEqual{T}(ReadOnlySpan{T}, ReadOnlySpan{T}) or another single-pass SIMD operation, which amortises the cache-miss cost over one contiguous traversal. For repeated access to the same data, a local copy via ArrayPool<T>.Shared.Rent is faster overall.

See Also