Class ByteBuffer
public class ByteBuffer : Buffer, IDynamicMetaObjectProvider, IJVMBridgeCore, IEquatable<IJVMBridgeBaseInstance>, IDisposable, IJVMBridgeBaseStatic, IJVMBridgeBase, IJVMBridgeBaseInstance, IJVMBridgeDefinition
- Inheritance
-
ByteBuffer
- Implements
- Derived
- Inherited Members
- Extension Methods
Constructors
ByteBuffer(IJVMBridgeBaseInitializer)
Initializer used internally by JCOBridge. Do not use directly.
[Obsolete("This public initializer is needed for JCOBridge internal use, other uses can produce unidentible behaviors.")]
public ByteBuffer(IJVMBridgeBaseInitializer initializer)
Parameters
initializerIJVMBridgeBaseInitializer
Properties
BridgeClassName
Java class name to be instantiated
public override string BridgeClassName { get; }
Property Value
IsBridgeAbstract
true if the BridgeClassName is an abstract class, i.e. cannot be created an instance
public override bool IsBridgeAbstract { get; }
Property Value
IsBridgeCloseable
true if the BridgeClassName implements java.lang.AutoCloseable
public override bool IsBridgeCloseable { get; }
Property Value
IsBridgeInterface
true if the BridgeClassName is an interface, i.e. does not have any public constructor
public override bool IsBridgeInterface { get; }
Property Value
IsBridgeStatic
true if the BridgeClassName is a static class, i.e. does not have any public constructor
public override bool IsBridgeStatic { get; }
Property Value
Methods
AlignedSlice(int)
public ByteBuffer AlignedSlice(int arg0)
Parameters
Returns
AlignmentOffset(int, int)
public int AlignmentOffset(int arg0, int arg1)
Parameters
Returns
Allocate(int)
public static ByteBuffer Allocate(int arg0)
Parameters
Returns
AllocateDirect(int)
public static ByteBuffer AllocateDirect(int arg0)
Parameters
Returns
AsCharBuffer()
public CharBuffer AsCharBuffer()
Returns
AsDoubleBuffer()
public DoubleBuffer AsDoubleBuffer()
Returns
AsFloatBuffer()
public FloatBuffer AsFloatBuffer()
Returns
AsIntBuffer()
public IntBuffer AsIntBuffer()
Returns
AsLongBuffer()
public LongBuffer AsLongBuffer()
Returns
AsReadOnlyBuffer()
public ByteBuffer AsReadOnlyBuffer()
Returns
AsShortBuffer()
public ShortBuffer AsShortBuffer()
Returns
AsSpan()
Returns a zero-copy ReadOnlySpan<T> over the entire buffer, starting at offset zero regardless of the current position.
public ReadOnlySpan<byte> AsSpan()
Returns
- ReadOnlySpan<byte>
A ReadOnlySpan<T> of length
buffer size / sizeof(backed directly by the native memory buffer.T)
Exceptions
- NotSupportedException
Thrown when the buffer exceeds MaxValue elements. Use
CopyTo(IntPtr)for buffers larger than 2 GB.
AsSpanFromIndex(int)
Returns a zero-copy ReadOnlySpan<T> over the buffer starting at the specified element index.
public ReadOnlySpan<byte> AsSpanFromIndex(int fromIndex)
Parameters
fromIndexintZero-based index of the first element to include in the span.
Returns
- ReadOnlySpan<byte>
A ReadOnlySpan<T> covering all elements from
fromIndexto the end of the buffer, backed directly by the native memory buffer.
Exceptions
- ArgumentOutOfRangeException
Thrown when
fromIndexis negative or greater than or equal to the element count.- NotSupportedException
Thrown when the number of remaining elements exceeds MaxValue.
AsWritableSpan()
Returns a zero-copy writable Span<T> 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()
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 Span<byte> AsWritableSpan()
Returns
- Span<byte>
A Span<T> of length
buffer limit / sizeof(backed directly by the native memory buffer.T)
Exceptions
- NotSupportedException
Thrown when the buffer exceeds MaxValue elements.
AsWritableSpanFromIndex(int)
Returns a zero-copy writable Span<T> 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()
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 Span<byte> AsWritableSpanFromIndex(int fromIndex)
Parameters
fromIndexintZero-based index of the first element to include in the span.
Returns
- Span<byte>
A Span<T> covering all elements from
fromIndexto the end of the buffer, backed directly by the native memory buffer.
Exceptions
- ArgumentOutOfRangeException
Thrown when
fromIndexis negative or greater than or equal to the element count.- NotSupportedException
Thrown when the number of remaining elements exceeds MaxValue.
Compact()
public ByteBuffer Compact()
Returns
CompareTo(ByteBuffer)
public int CompareTo(ByteBuffer arg0)
Parameters
arg0ByteBuffer
Returns
CompareTo(object)
public int CompareTo(object arg0)
Parameters
Returns
Dispose(bool)
Implements the pattern described in https://learn.microsoft.com/en-en/dotnet/standard/garbage-collection/implementing-dispose
protected override void Dispose(bool disposing)
Parameters
disposingboolThe disposing parameter is a bool that indicates whether the method call comes from a Dispose() method (its value is true) or from a finalizer (its value is false)
FlushOnDispose()
Marks this stream to flush all native memory changes back to the underlying resource on Dispose().
Must be called after any direct write performed through AsWritableSpan() or AsWritableSpanFromIndex(int) before the stream is closed.
This method is idempotent — calling it multiple times has no additional effect.
public void FlushOnDispose()
From(JCOBridgeSharedBufferStream<byte>)
Creates a new ByteBuffer in the JVM which shares the memory of stream.
This is the preferred overload for high-rate scenarios as it avoids repeated array copies from CLR to JVM and benefits from pooled buffer management.
public static ByteBuffer From(JCOBridgeSharedBufferStream<byte> stream)
Parameters
streamJCOBridgeSharedBufferStream<byte>A JCOBridgeSharedBufferStream<T> obtained from Rent(long) and populated via Stream-based APIs, to be used directly within the JVM from a ByteBuffer.
Returns
- ByteBuffer
A new instance of ByteBuffer holding the memory of
streamshared with the ByteBuffer.
Remarks
The memory associated to stream will be retained until the JVM reference of the newly created ByteBuffer is garbage collected.
Under heavy pressure the memory footprint can raise up and generate an OutOfMemoryException; use the functionality with caution.
Lifecycle management: the subsystem automatically returns stream to the internal pool once the JVM Garbage Collector retires the associated
ByteBuffer, i.e. when the ByteBuffer has been fully consumed by the JVM.
A direct call to Dispose() on the returned ByteBuffer is therefore a no-op; do not attempt to manually dispose stream after passing it to this method.
Pool strategy: the HPA (High Performance Application) runtime variant draws stream instances from a highly optimized pool tuned for high-throughput workloads,
while the standard runtime variant uses a lighter pool. In both cases the pooling is fully transparent to the caller.
Exceptions
- ArgumentException
Thrown when
streamwas not obtained through Rent(long).- NotSupportedException
Thrown when the JVM is unable to generate a ByteBuffer instance.
From(byte[], bool, int)
Creates a new ByteBuffer in the JVM which belongs to data
public static ByteBuffer From(byte[] data, bool arrangeCapacity = true, int timeToLive = -1)
Parameters
databyte[]The data to be shared
arrangeCapacityboolIf true the byte array in
datawill be resized to the next power of 2, so capacity will be memory aligned and the limit of ByteBuffer will be current size ofdatatimeToLiveintThe time to live, expressed in milliseconds, the underlying memory shall remain available; if the time to live expires the pinned memory is retired leaving potentially the JVM under the possibility of an access violation.
Returns
- ByteBuffer
A new instance of ByteBuffer holding the memory of
data
Remarks
The memory associated to data will be pinned until the JVM reference of the newly created ByteBuffer is garbage collected to avoid access violation within the JVM.
Under heavy pressure the memory footprint can raise up and generate an OutOfMemoryException, use the functionality with caution or take into account the timeToLive option which can help to recover the memory in advance before the Garbage Collector of the JVM retires the ByteBuffer
If the user of ByteBuffer is pretty sure that the pinned memory is no more needed from the JVM, e.g. the invoked method does not queue the ByteBuffer and its lifetime ends when the method returns; to immediately release unmanaged resources, and free the memory, invokes ToDirectBuffer(bool) and invoke Dispose()
From(MemoryStream, EventHandler<MemoryStream>, int)
Creates a new ByteBuffer in the JVM which shares the stream. The method helps to avoid too many array copies from CLR to JVM
public static ByteBuffer From(MemoryStream stream, EventHandler<MemoryStream> disposeEvent = null, int timeToLive = -1)
Parameters
streamMemoryStreamThe non disposed MemoryStream to be used directly within the JVM from a ByteBuffer, see remarks
disposeEventEventHandler<MemoryStream>An optional EventHandler<TEventArgs> can be used to be informed when the
streamcan be safely disposed (the dispose action shall be in the user code), if null the underlying system will automatically dispose the MemoryStream.timeToLiveintThe time to live, expressed in milliseconds, the underlying memory shall remain available; if the time to live expires the pinned memory is retired leaving potentially the JVM under the possibility of an access violation.
Returns
- ByteBuffer
A new instance of ByteBuffer holding the memory of
streamshared with the ByteBuffer
Remarks
The memory associated to stream will be pinned until the JVM reference of the newly created ByteBuffer is garbage collected to avoid access violation within the JVM.
Under heavy pressure the memory footprint can raise up and generate an OutOfMemoryException, use the functionality with caution or take into account the timeToLive option which can help to recover the memory in advance before the Garbage Collector of the JVM retires the ByteBuffer
The MemoryStream cannot be disposed otherwise the underlying system is not able to access the memory. The MemoryStream can be written, or read, and changes are visible to both CLR and JVM, however, if the MemoryStream grows, the underlying system cannot resize too and capacity still remains the one when From(MemoryStream, EventHandler<MemoryStream>, int) was invoked the first time.
From(nint, long, EventHandler<object>, object, int)
Creates a new ByteBuffer in the JVM which belongs to rawAddr.
public static ByteBuffer From(nint rawAddr, long capacity, EventHandler<object> disposeEvent = null, object disposeEventState = null, int timeToLive = -1)
Parameters
rawAddrnintThe pointer where data is stored
capacitylongDeclares the memory available, in byte, associated to
rawAddrdisposeEventEventHandler<object>An optional EventHandler<TEventArgs> can be used to be informed when the
rawAddrcan be safely retired becuase the JVM is no moore using the pointer ofrawAddr.disposeEventStateobjectThe data will be associated to
disposeEvent, by default the value will berawAddrtimeToLiveintThe time to live, expressed in milliseconds, the underlying memory shall remain available; if the time to live expires the pinned memory is retired leaving potentially the JVM under the possibility of an access violation.
Returns
- ByteBuffer
A new instance of ByteBuffer holding the memory of
rawAddr
Remarks
The memory associated to rawAddr shall be available until the JVM reference of the newly created ByteBuffer is garbage collected to avoid access violation within the JVM.
Under heavy pressure the memory footprint can raise up and generate an OutOfMemoryException, use the functionality with caution or take into account the timeToLive option which can help to recover the memory in advance before the Garbage Collector of the JVM retires the ByteBuffer
If the user of ByteBuffer is pretty sure that the memory is no more needed from the JVM, e.g. the invoked method does not queue the ByteBuffer and its lifetime ends when the method returns; to immediately release unmanaged resources, and free the memory, invokes ToDirectBuffer(bool) and invoke Dispose()
Get()
public byte Get()
Returns
Get(byte[])
public ByteBuffer Get(byte[] arg0)
Parameters
Returns
Get(byte[], int, int)
public ByteBuffer Get(byte[] arg0, int arg1, int arg2)
Parameters
Returns
Get(int)
public byte Get(int arg0)
Parameters
Returns
Get(int, byte[])
public ByteBuffer Get(int arg0, byte[] arg1)
Parameters
Returns
Get(int, byte[], int, int)
public ByteBuffer Get(int arg0, byte[] arg1, int arg2, int arg3)
Parameters
Returns
GetChar()
public char GetChar()
Returns
GetChar(int)
public char GetChar(int arg0)
Parameters
Returns
GetDouble()
public double GetDouble()
Returns
GetDouble(int)
public double GetDouble(int arg0)
Parameters
Returns
GetFloat()
public float GetFloat()
Returns
GetFloat(int)
public float GetFloat(int arg0)
Parameters
Returns
GetInt()
public int GetInt()
Returns
GetInt(int)
public int GetInt(int arg0)
Parameters
Returns
GetLong()
public long GetLong()
Returns
GetLong(int)
public long GetLong(int arg0)
Parameters
Returns
GetShort()
public short GetShort()
Returns
GetShort(int)
public short GetShort(int arg0)
Parameters
Returns
Mismatch(ByteBuffer)
public int Mismatch(ByteBuffer arg0)
Parameters
arg0ByteBuffer
Returns
Order()
public ByteOrder Order()
Returns
Order(ByteOrder)
public ByteBuffer Order(ByteOrder arg0)
Parameters
Returns
Put(ByteBuffer)
public ByteBuffer Put(ByteBuffer arg0)
Parameters
arg0ByteBuffer
Returns
Put(byte)
public ByteBuffer Put(byte arg0)
Parameters
Returns
Put(byte[])
public ByteBuffer Put(byte[] arg0)
Parameters
Returns
Put(byte[], int, int)
public ByteBuffer Put(byte[] arg0, int arg1, int arg2)
Parameters
Returns
Put(int, ByteBuffer, int, int)
public ByteBuffer Put(int arg0, ByteBuffer arg1, int arg2, int arg3)
Parameters
arg0intarg1ByteBufferarg2intarg3int
Returns
Put(int, byte)
public ByteBuffer Put(int arg0, byte arg1)
Parameters
Returns
Put(int, byte[])
public ByteBuffer Put(int arg0, byte[] arg1)
Parameters
Returns
Put(int, byte[], int, int)
public ByteBuffer Put(int arg0, byte[] arg1, int arg2, int arg3)
Parameters
Returns
PutChar(char)
public ByteBuffer PutChar(char arg0)
Parameters
Returns
PutChar(int, char)
public ByteBuffer PutChar(int arg0, char arg1)
Parameters
Returns
PutDouble(double)
public ByteBuffer PutDouble(double arg0)
Parameters
Returns
PutDouble(int, double)
public ByteBuffer PutDouble(int arg0, double arg1)
Parameters
Returns
PutFloat(int, float)
public ByteBuffer PutFloat(int arg0, float arg1)
Parameters
Returns
PutFloat(float)
public ByteBuffer PutFloat(float arg0)
Parameters
Returns
PutInt(int)
public ByteBuffer PutInt(int arg0)
Parameters
Returns
PutInt(int, int)
public ByteBuffer PutInt(int arg0, int arg1)
Parameters
Returns
PutLong(int, long)
public ByteBuffer PutLong(int arg0, long arg1)
Parameters
Returns
PutLong(long)
public ByteBuffer PutLong(long arg0)
Parameters
Returns
PutShort(short)
public ByteBuffer PutShort(short arg0)
Parameters
Returns
PutShort(int, short)
public ByteBuffer PutShort(int arg0, short arg1)
Parameters
Returns
Rent(long)
Returns a JCOBridgeSharedBufferStream<T> with an initial capacity derived from capacity,
to be populated via Stream-based APIs and then passed to From(JCOBridgeSharedBufferStream<byte>).
public static JCOBridgeSharedBufferStream<byte> Rent(long capacity = -1)
Parameters
capacitylongThe plausible number of elements of byte type to be written into the stream; the byte size is computed as
capacity * sizeof(byte). The default value of-1instructs the subsystem to allocate the minimum meaningful unit, which corresponds to one system memory page (see SystemPageSize). Regardless of the value provided, the effective allocation is always rounded up to the nearest multiple of the system page size, since the underlying native allocator operates at page granularity. Passing a value smaller than one page therefore has no practical advantage over using the default. This value is a hint, not a hard limit: if the actual data written exceeds the initial allocation, the underlying buffer will grow automatically via reallocation. However, providing a value greater than or equal to the actual data size is strongly recommended to avoid reallocation overhead, especially in high-rate scenarios. Callers that process data of a known or predictable size are encouraged to implement their own estimation strategy — for example, tracking the stable size observed in previous invocations — so that the initial capacity converges toward the real value over time and reallocations become increasingly rare or disappear entirely.
Returns
- JCOBridgeSharedBufferStream<byte>
A pooled instance of JCOBridgeSharedBufferStream<T> ready to be written via Stream-based APIs and then passed to From(JCOBridgeSharedBufferStream<byte>).
Remarks
The returned JCOBridgeSharedBufferStream<T> is drawn from an internal pool. The HPA (High Performance Application) runtime variant uses a highly optimized pool tuned for high-throughput scenarios, while the standard runtime variant uses a lighter pool suitable for moderate workloads. The instance must not be manually disposed; its lifecycle is fully managed by the subsystem and it is automatically returned to the pool once the JVM Garbage Collector retires the associated ByteBuffer created by From(JCOBridgeSharedBufferStream<byte>).
Exceptions
- ArgumentOutOfRangeException
Thrown when
capacityis zero or any positive value that, once multiplied bysizeof(byte), overflows a long.
ToArray(bool)
Returns the byte array managed from this ByteBuffer
public byte[] ToArray(bool bypassDirectConvert = false)
Parameters
Returns
- byte[]
The byte array managed from this ByteBuffer
ToArray(ref byte[], bool)
Fills the array with data managed from this ByteBuffer
public void ToArray(ref byte[] array, bool resizeToFill = true)
Parameters
arraybyte[]The array to be filled with the content of the ByteBuffer
resizeToFillboolResize
arrayto contain all data available in the ByteBuffer
ToDirectBuffer(bool)
Returns an instance of JCOBridgeDirectBuffer<T> can be used to directly access and manages JVM memory without any memory move
[Obsolete("DO NOT CALL Dispose() on the returned JCOBridgeDirectBuffer: it is an internal instance whose lifetime is managed by the owning object.", false)]
public JCOBridgeDirectBuffer<byte> ToDirectBuffer(bool rewind)
Parameters
rewindboolRewind() the instance before return JCOBridgeDirectBuffer<T>
Returns
- JCOBridgeDirectBuffer<byte>
The JCOBridgeDirectBuffer<T> associated to this ByteBuffer instance
Remarks
Do not call Dispose() on the returned instance. Its lifetime is managed by the owning object.
ToStream()
Returns an instance of Stream associated to this ByteBuffer instance
public Stream ToStream()
Returns
- Stream
The Stream associated to this ByteBuffer instance
Remarks
The returned Stream can be used to directly access and manages JVM memory without any memory move
Wrap(byte[])
public static ByteBuffer Wrap(byte[] arg0)
Parameters
Returns
Wrap(byte[], int, int)
public static ByteBuffer Wrap(byte[] arg0, int arg1, int arg2)
Parameters
Returns
Operators
implicit operator Comparable(ByteBuffer)
Converter from ByteBuffer to Comparable
public static implicit operator Comparable(ByteBuffer t)
Parameters
Returns
implicit operator Comparable<ByteBuffer>(ByteBuffer)
Converter from ByteBuffer to Comparable<T>
public static implicit operator Comparable<ByteBuffer>(ByteBuffer buffer)
Parameters
bufferByteBuffer
Returns
implicit operator JCOBridgeDirectBuffer<byte>(ByteBuffer)
Converts an instance of ByteBuffer into JCOBridgeDirectBuffer<T>
public static implicit operator JCOBridgeDirectBuffer<byte>(ByteBuffer t)
Parameters
Returns
implicit operator byte[](ByteBuffer)
Converts an instance of ByteBuffer into byte array
public static implicit operator byte[](ByteBuffer t)
Parameters
Returns
- byte[]
Remarks
If the ByteBuffer supports direct access the function tries to move data from JVM memory without JNI, otherwise fallback to the standard memory copy.
implicit operator Stream(ByteBuffer)
Converts an instance of ByteBuffer into Stream
public static implicit operator Stream(ByteBuffer t)
Parameters
Returns
Remarks
The returned Stream can be used to directly access and manages JVM memory without any memory move
implicit operator ByteBuffer(byte[])
Converts an instance of byte array into ByteBuffer using the default parameters of From(byte[], bool, int)
public static implicit operator ByteBuffer(byte[] t)
Parameters
tbyte[]
Returns
Remarks
If the JVM supports direct access the function will share with the JVM the memory without JNI, otherwise fallback to the standard memory copy.
implicit operator ByteBuffer(MemoryStream)
Converts an instance of MemoryStream into a ByteBuffer using the default parameters of From(MemoryStream, EventHandler<MemoryStream>, int)
public static implicit operator ByteBuffer(MemoryStream stream)
Parameters
streamMemoryStream
Returns
Remarks
See remarks of From(MemoryStream, EventHandler<MemoryStream>, int)