UnmanagedMemoryStream UnmanagedMemoryStream UnmanagedMemoryStream UnmanagedMemoryStream Class

定义

重要

此 API 不符合 CLS。

提供从托管代码访问非托管内存块的能力。Provides access to unmanaged blocks of memory from managed code.

public ref class UnmanagedMemoryStream : System::IO::Stream
[System.CLSCompliant(false)]
public class UnmanagedMemoryStream : System.IO.Stream
type UnmanagedMemoryStream = class
    inherit Stream
Public Class UnmanagedMemoryStream
Inherits Stream
继承
UnmanagedMemoryStreamUnmanagedMemoryStreamUnmanagedMemoryStreamUnmanagedMemoryStream
派生
属性

示例

下面的代码示例演示如何读取和写入到非托管的内存使用UnmanagedMemoryStream类。The following code example demonstrates how to read from and write to unmanaged memory using the UnmanagedMemoryStream class. 非托管内存块进行分配和解除分配使用Marshal类。A block of unmanaged memory is allocated and de-allocated using the Marshal class.


// Note: you must compile this sample using the unsafe flag.
// From the command line, type the following: csc sample.cs /unsafe

using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;

unsafe class TestWriter
{
    static void Main()
    {
        // Create some data to read and write.
        byte[] message = UnicodeEncoding.Unicode.GetBytes("Here is some data.");

        // Allocate a block of unmanaged memory and return an IntPtr object.	
        IntPtr memIntPtr = Marshal.AllocHGlobal(message.Length);

        // Get a byte pointer from the IntPtr object.
        byte* memBytePtr = (byte*)memIntPtr.ToPointer();

        // Create an UnmanagedMemoryStream object using a pointer to unmanaged memory.
        UnmanagedMemoryStream writeStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Write);

        // Write the data.
        writeStream.Write(message, 0, message.Length);

        // Close the stream.
        writeStream.Close();

        // Create another UnmanagedMemoryStream object using a pointer to unmanaged memory.
        UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Read);

        // Create a byte array to hold data from unmanaged memory.
        byte[] outMessage = new byte[message.Length];

        // Read from unmanaged memory to the byte array.
        readStream.Read(outMessage, 0, message.Length);

        // Close the stream.
        readStream.Close();

        // Display the data to the console.
        Console.WriteLine(UnicodeEncoding.Unicode.GetString(outMessage));

        // Free the block of unmanaged memory.
        Marshal.FreeHGlobal(memIntPtr);

        Console.ReadLine();
    }
}

注解

此类支持对非托管内存使用现有的基于流的模型的访问,不需要非托管内存中的内容被复制到堆。This class supports access to unmanaged memory using the existing stream-based model and does not require that the contents in the unmanaged memory be copied to the heap.

备注

此类型可实现 IDisposable 接口,但实际上没有任何要释放的资源。This type implements the IDisposable interface, but does not actually have any resources to dispose. 这意味着无需通过直接调用 Dispose() 或使用语言构造(C# 中的 using 或 Visual Basic 中的 Using)对其进行处理。This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.

构造函数

UnmanagedMemoryStream() UnmanagedMemoryStream() UnmanagedMemoryStream() UnmanagedMemoryStream()

初始化 UnmanagedMemoryStream 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class.

UnmanagedMemoryStream(Byte*, Int64) UnmanagedMemoryStream(Byte*, Int64) UnmanagedMemoryStream(Byte*, Int64) UnmanagedMemoryStream(Byte*, Int64)

用指定的位置和内存长度初始化 UnmanagedMemoryStream 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class using the specified location and memory length.

UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess)

使用指定的位置、内存长度、内存总量和文件访问值初始化 UnmanagedMemoryStream 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class using the specified location, memory length, total amount of memory, and file access values.

UnmanagedMemoryStream(SafeBuffer, Int64, Int64) UnmanagedMemoryStream(SafeBuffer, Int64, Int64) UnmanagedMemoryStream(SafeBuffer, Int64, Int64) UnmanagedMemoryStream(SafeBuffer, Int64, Int64)

在具有指定的偏移量和长度的安全缓冲区中初始化 UnmanagedMemoryStream 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset and length.

UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess)

在具有指定的偏移量、长度和文件访问的安全缓冲区中初始化 UnmanagedMemoryStream 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset, length, and file access.

属性

CanRead CanRead CanRead CanRead

获取一个值,该值指示流是否支持读取。Gets a value indicating whether a stream supports reading.

CanSeek CanSeek CanSeek CanSeek

获取一个值,该值指示流是否支持查找。Gets a value indicating whether a stream supports seeking.

CanTimeout CanTimeout CanTimeout CanTimeout

获取一个值,该值确定当前流是否可以超时。Gets a value that determines whether the current stream can time out.

(Inherited from Stream)
CanWrite CanWrite CanWrite CanWrite

获取一个值,该值指示流是否支持写入。Gets a value indicating whether a stream supports writing.

Capacity Capacity Capacity Capacity

获取流的长度(大小)或分配给流的内存总量(容量)。Gets the stream length (size) or the total amount of memory assigned to a stream (capacity).

Length Length Length Length

获取流中数据的长度。Gets the length of the data in a stream.

Position Position Position Position

获取或设置流中的当前位置。Gets or sets the current position in a stream.

PositionPointer PositionPointer PositionPointer PositionPointer

获取或设置基于流中当前位置的指向流的字节指针。Gets or sets a byte pointer to a stream based on the current position in the stream.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试读取多长时间。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(Inherited from Stream)
WriteTimeout WriteTimeout WriteTimeout WriteTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试写入多长时间。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(Inherited from Stream)

方法

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步读操作。Begins an asynchronous read operation. (请考虑改用 ReadAsync(Byte[], Int32, Int32)。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

开始异步写操作。Begins an asynchronous write operation. (请考虑改用 WriteAsync(Byte[], Int32, Int32)。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
Close() Close() Close() Close()

关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)。Closes 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)
CopyTo(Stream) CopyTo(Stream) CopyTo(Stream) CopyTo(Stream)

从当前流中读取字节并将其写入到另一流中。Reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32)

使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中。Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream)

从当前流中异步读取字节并将其写入到另一个流中。Asynchronously reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken)

通过指定的取消令牌,从当前流中异步读取字节并将其写入到另一个流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(Inherited from Stream)
CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32)

使用指定的缓冲区大小,从当前流中异步读取字节并将其写入到另一流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(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)
CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateWaitHandle() CreateWaitHandle() CreateWaitHandle() CreateWaitHandle()

分配 WaitHandle 对象。Allocates a WaitHandle object.

(Inherited from Stream)
Dispose() Dispose() Dispose() Dispose()

释放由 Stream 使用的所有资源。Releases all resources used by the Stream.

(Inherited from Stream)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 UnmanagedMemoryStream 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the UnmanagedMemoryStream and optionally releases the managed resources.

DisposeAsync() DisposeAsync() DisposeAsync() DisposeAsync()

异步释放 Stream 使用的非托管资源。Asynchronously releases the unmanaged resources used by the Stream.

(Inherited from Stream)
EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult)

等待挂起的异步读取完成。Waits for the pending asynchronous read to complete. (请考虑改用 ReadAsync(Byte[], Int32, Int32)。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult)

结束异步写操作。Ends an asynchronous write operation. (请考虑改用 WriteAsync(Byte[], Int32, Int32)。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush() Flush() Flush() Flush()

重写 Flush() 方法以便不执行任何操作。Overrides the Flush() method so that no action is performed.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中。Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from Stream)
FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken)

重写 FlushAsync(CancellationToken) 方法,以便取消操作(如果已指定),但不执行其他任何操作。Overrides the FlushAsync(CancellationToken) method so that the operation is cancelled if specified, but no other action is performed.

从 .NET Framework 4.6 开始可用Available starting in .NET Framework 4.6

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
Initialize(Byte*, Int64, Int64, FileAccess) Initialize(Byte*, Int64, Int64, FileAccess) Initialize(Byte*, Int64, Int64, FileAccess) Initialize(Byte*, Int64, Int64, FileAccess)

使用指向非托管内存位置的指针初始化 UnmanagedMemoryStream 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class by using a pointer to an unmanaged memory location.

Initialize(SafeBuffer, Int64, Int64, FileAccess) Initialize(SafeBuffer, Int64, Int64, FileAccess) Initialize(SafeBuffer, Int64, Int64, FileAccess) Initialize(SafeBuffer, Int64, Int64, FileAccess)

在具有指定的偏移量、长度和文件访问的安全缓冲区中初始化 UnmanagedMemoryStream 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset, length, and file access.

InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ObjectInvariant() ObjectInvariant() ObjectInvariant() ObjectInvariant()

提供对 Contract 的支持。Provides support for a Contract.

(Inherited from Stream)
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

将指定数量的字节读入指定的数组。Reads the specified number of bytes into the specified array.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)
ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(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)
ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken)

将指定数量的字节异步读入指定的数组。Asynchronously reads the specified number of bytes into the specified array.

从 .NET Framework 4.6 开始可用Available starting in .NET Framework 4.6

ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken)
ReadByte() ReadByte() ReadByte() ReadByte()

从流中读取一个字节,并将流内的位置前移一个字节,或者如果已到达流的末尾,则返回 -1。Reads 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.

Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

将当前流的当前位置设置为给定值。Sets the current position of the current stream to the given value.

SetLength(Int64) SetLength(Int64) SetLength(Int64) SetLength(Int64)

将流的长度设置为指定的值。Sets the length of a stream to a specified value.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

使用缓冲区中的数据将字节块写入当前流。Writes a block of bytes to the current stream using data from a buffer.

Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>)
WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(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)
WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(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.

从 .NET Framework 4.6 开始可用Available starting in .NET Framework 4.6

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)
WriteByte(Byte) WriteByte(Byte) WriteByte(Byte) WriteByte(Byte)

一个字节写入文件流中的当前位置。Writes a byte to the current position in the file stream.

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

释放由 Stream 使用的所有资源。Releases all resources used by the Stream.

(Inherited from Stream)

扩展方法

AsInputStream(Stream) AsInputStream(Stream) AsInputStream(Stream) AsInputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输入流。Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream) AsOutputStream(Stream) AsOutputStream(Stream) AsOutputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输出流。Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime.

AsRandomAccessStream(Stream) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream)

将指定的流转换为随机访问流。Converts the specified stream to a random access stream.

适用于