UnmanagedMemoryStream 类

定义

重要

此 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
继承
UnmanagedMemoryStream
派生
属性

示例

下面的代码示例演示如何使用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 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class.

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 类的新实例。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 类的新实例。Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset and length.

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

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

CanSeek

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

CanTimeout

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

(继承自 Stream)
CanWrite

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

Capacity

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

Length

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

Position

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

PositionPointer

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

ReadTimeout

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

(继承自 Stream)
WriteTimeout

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

(继承自 Stream)

方法

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

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

(继承自 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

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

(继承自 Stream)
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.

(继承自 Stream)
CopyTo(Stream)

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

(继承自 Stream)
CopyTo(Stream, Int32)

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

(继承自 Stream)
CopyToAsync(Stream)

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

(继承自 Stream)
CopyToAsync(Stream, CancellationToken)

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

(继承自 Stream)
CopyToAsync(Stream, Int32)

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

(继承自 Stream)
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.

(继承自 Stream)
CreateObjRef(Type)

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

(继承自 MarshalByRefObject)
CreateWaitHandle()

分配 WaitHandle 对象。Allocates a WaitHandle object.

(继承自 Stream)
Dispose()

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

(继承自 Stream)
Dispose(Boolean)

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

DisposeAsync()

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

(继承自 Stream)
EndRead(IAsyncResult)

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

(继承自 Stream)
EndWrite(IAsyncResult)

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

(继承自 Stream)
Equals(Object)

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

(继承自 Object)
Flush()

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

FlushAsync()

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

(继承自 Stream)
FlushAsync(CancellationToken)

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

GetHashCode()

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

(继承自 Object)
GetLifetimeService()

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

(继承自 MarshalByRefObject)
GetType()

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

(继承自 Object)
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)

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

InitializeLifetimeService()

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

(继承自 MarshalByRefObject)
MemberwiseClone()

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

(继承自 Object)
MemberwiseClone(Boolean)

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

(继承自 MarshalByRefObject)
ObjectInvariant()

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

(继承自 Stream)
Read(Byte[], Int32, Int32)

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

Read(Span<Byte>)

将此非管理的内存流的所有字节读入指定的字节跨度。Reads all the bytes of this unmanaged memory stream into the specified span of bytes.

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.

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

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

ReadAsync(Memory<Byte>, CancellationToken)

以异步方式将非管理的内存流字节读入内存区域。Asynchronously reads the unmanaged memory stream bytes into the memory region.

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)

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

SetLength(Int64)

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

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
Write(Byte[], Int32, Int32)

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

Write(ReadOnlySpan<Byte>)

使用来自提供的字节跨度的数据将字节块写入当前非管理的内存流。Writes a block of bytes to the current unmanaged memory stream using data from the provided span of bytes.

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.

(继承自 Stream)
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.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将字节跨度异步写入当前流,按写入的字节数向前移动该流中的当前位置,并监视取消请求。Asynchronously writes a span of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteByte(Byte)

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

显式界面实现

IDisposable.Dispose()

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

(继承自 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)

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

AsRandomAccessStream(Stream)

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

适用于