UnmanagedMemoryStream Constructores

Definición

Inicializa una nueva instancia de la clase UnmanagedMemoryStream.

Sobrecargas

UnmanagedMemoryStream()

Inicializa una nueva instancia de la clase UnmanagedMemoryStream.

UnmanagedMemoryStream(Byte*, Int64)

Inicializa una instancia nueva de la clase UnmanagedMemoryStream utilizando la ubicación y la longitud de memoria especificadas.

UnmanagedMemoryStream(SafeBuffer, Int64, Int64)

Inicializa una nueva instancia de la clase UnmanagedMemoryStream en un búfer seguro con un desplazamiento y una longitud especificados.

UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess)

Inicializa una instancia nueva de la clase UnmanagedMemoryStream utilizando los valores especificados de ubicación, longitud de memoria, cantidad total de memoria y acceso a archivos.

UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess)

Inicializa una nueva instancia de la clase UnmanagedMemoryStream en un búfer seguro con un desplazamiento, una longitud y un acceso a archivo especificados.

UnmanagedMemoryStream()

Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs

Inicializa una nueva instancia de la clase UnmanagedMemoryStream.

protected:
 UnmanagedMemoryStream();
protected UnmanagedMemoryStream ();
Protected Sub New ()

Excepciones

El usuario no dispone del permiso requerido.

Se aplica a

UnmanagedMemoryStream(Byte*, Int64)

Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs

Importante

Esta API no es conforme a CLS.

Inicializa una instancia nueva de la clase UnmanagedMemoryStream utilizando la ubicación y la longitud de memoria especificadas.

public:
 UnmanagedMemoryStream(System::Byte* pointer, long length);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public UnmanagedMemoryStream (byte* pointer, long length);
[System.CLSCompliant(false)]
public UnmanagedMemoryStream (byte* pointer, long length);
public UnmanagedMemoryStream (byte* pointer, long length);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 -> System.IO.UnmanagedMemoryStream
[<System.CLSCompliant(false)>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 -> System.IO.UnmanagedMemoryStream
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 -> System.IO.UnmanagedMemoryStream

Parámetros

pointer
Byte*

Puntero a una ubicación de memoria no administrada.

length
Int64

Longitud de la memoria que se va a utilizar.

Atributos

Excepciones

El usuario no dispone del permiso requerido.

El valor pointer es null.

El valor de length es menor que cero.

o bien

El valor de length es suficientemente alto como para causar un desbordamiento.

Ejemplos

En el ejemplo de código siguiente se muestra cómo leer y escribir en memoria no administrada mediante la UnmanagedMemoryStream clase . Se asigna un bloque de memoria no administrada y se desasigna mediante la Marshal clase .

// 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.Runtime.InteropServices;
using System.Text;

unsafe class Program
{
    static void Main()
    {
        // Create some data to write.
        byte[] text = UnicodeEncoding.Unicode.GetBytes("Data to write.");

        // Allocate a block of unmanaged memory.
        IntPtr memIntPtr = Marshal.AllocHGlobal(text.Length);

        // Get a byte pointer from the unmanaged memory block.
        byte* memBytePtr = (byte*)memIntPtr.ToPointer();

        UnmanagedMemoryStream writeStream =
            new UnmanagedMemoryStream(
            memBytePtr, text.Length, text.Length, FileAccess.Write);

        // Write the data.
        WriteToStream(writeStream, text);

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

        // Create another UnmanagedMemoryStream for reading.
        UnmanagedMemoryStream readStream =
            new UnmanagedMemoryStream(memBytePtr, text.Length);

        // Display the contents of the stream to the console.
        PrintStream(readStream);

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

        // Free up the unmanaged memory.
        Marshal.FreeHGlobal(memIntPtr);
    }

    public static void WriteToStream(UnmanagedMemoryStream writeStream, byte[] text)
    {
        // Verify that the stream is writable:
        // By default, UnmanagedMemoryStream objects do not have write access,
        // write access must be set explicitly.
        if (writeStream.CanWrite)
        {
            // Write the data, byte by byte
            for (int i = 0; i < writeStream.Length; i++)
            {
                writeStream.WriteByte(text[i]);
            }
        }
    }

    public static void PrintStream(UnmanagedMemoryStream readStream)
    {
        byte[] text = new byte[readStream.Length];
        // Verify that the stream is writable:
        // By default, UnmanagedMemoryStream objects do not have write access,
        // write access must be set explicitly.
        if (readStream.CanRead)
        {
            // Write the data, byte by byte
            for (int i = 0; i < readStream.Length; i++)
            {
                text[i] = (byte)readStream.ReadByte();
            }
        }

        Console.WriteLine(UnicodeEncoding.Unicode.GetString(text));
    }
}

Comentarios

Este constructor crea una nueva instancia de la UnmanagedMemoryStream clase y, de forma predeterminada, establece la CanWrite propiedad false en y la CanRead propiedad en true. La Length propiedad se establece en el valor del length parámetro y no se puede cambiar.

Se aplica a

UnmanagedMemoryStream(SafeBuffer, Int64, Int64)

Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs

Inicializa una nueva instancia de la clase UnmanagedMemoryStream en un búfer seguro con un desplazamiento y una longitud especificados.

public:
 UnmanagedMemoryStream(System::Runtime::InteropServices::SafeBuffer ^ buffer, long offset, long length);
public UnmanagedMemoryStream (System.Runtime.InteropServices.SafeBuffer buffer, long offset, long length);
new System.IO.UnmanagedMemoryStream : System.Runtime.InteropServices.SafeBuffer * int64 * int64 -> System.IO.UnmanagedMemoryStream
Public Sub New (buffer As SafeBuffer, offset As Long, length As Long)

Parámetros

buffer
SafeBuffer

Búfer que va a contener la secuencia de memoria no administrada.

offset
Int64

Posición de byte del búfer en la que va a comenzar la secuencia de memoria no administrada.

length
Int64

Longitud de la secuencia de memoria no administrada.

Se aplica a

UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess)

Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs

Importante

Esta API no es conforme a CLS.

Inicializa una instancia nueva de la clase UnmanagedMemoryStream utilizando los valores especificados de ubicación, longitud de memoria, cantidad total de memoria y acceso a archivos.

public:
 UnmanagedMemoryStream(System::Byte* pointer, long length, long capacity, System::IO::FileAccess access);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public UnmanagedMemoryStream (byte* pointer, long length, long capacity, System.IO.FileAccess access);
[System.CLSCompliant(false)]
public UnmanagedMemoryStream (byte* pointer, long length, long capacity, System.IO.FileAccess access);
public UnmanagedMemoryStream (byte* pointer, long length, long capacity, System.IO.FileAccess access);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream
[<System.CLSCompliant(false)>]
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream
new System.IO.UnmanagedMemoryStream : nativeptr<byte> * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream

Parámetros

pointer
Byte*

Puntero a una ubicación de memoria no administrada.

length
Int64

Longitud de la memoria que se va a utilizar.

capacity
Int64

Cantidad total de memoria asignada a la secuencia.

access
FileAccess

Uno de los valores de FileAccess.

Atributos

Excepciones

El usuario no dispone del permiso requerido.

El valor pointer es null.

El valor de length es menor que cero.

o bien

El valor de capacity es menor que cero.

o bien

El valor de length es mayor que el valor de capacity.

Ejemplos

En el ejemplo de código siguiente se muestra cómo leer y escribir en memoria no administrada mediante la UnmanagedMemoryStream clase . Se asigna un bloque de memoria no administrada y se desasigna mediante la Marshal clase .


// 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();
    }
}

Comentarios

El length parámetro define la cantidad actual de memoria en uso. Si lee o anexa datos a la secuencia, el length valor debe ser igual a la cantidad de datos válidos de la secuencia que se van a leer o conservar. Si escribe en la secuencia, este valor debe ser cero.

El capacity parámetro indica la cantidad de memoria total disponible. Este valor puede describir una región más larga que la longitud especificada o indicar una región a la que se puede anexar. Se producirá un error en cualquier intento de escritura más allá de este valor.

El access parámetro establece las CanReadpropiedades , y CanWrite . Tenga en cuenta que especificar Write no garantiza que la secuencia se pueda escribir. Los parámetros de acceso permiten al implementador crear un objeto cuya implementación puede coincidir con la secuencia real que se expone.

Se aplica a

UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess)

Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs
Source:
UnmanagedMemoryStream.cs

Inicializa una nueva instancia de la clase UnmanagedMemoryStream en un búfer seguro con un desplazamiento, una longitud y un acceso a archivo especificados.

public:
 UnmanagedMemoryStream(System::Runtime::InteropServices::SafeBuffer ^ buffer, long offset, long length, System::IO::FileAccess access);
public UnmanagedMemoryStream (System.Runtime.InteropServices.SafeBuffer buffer, long offset, long length, System.IO.FileAccess access);
new System.IO.UnmanagedMemoryStream : System.Runtime.InteropServices.SafeBuffer * int64 * int64 * System.IO.FileAccess -> System.IO.UnmanagedMemoryStream
Public Sub New (buffer As SafeBuffer, offset As Long, length As Long, access As FileAccess)

Parámetros

buffer
SafeBuffer

Búfer que va a contener la secuencia de memoria no administrada.

offset
Int64

Posición de byte del búfer en la que va a comenzar la secuencia de memoria no administrada.

length
Int64

Longitud de la secuencia de memoria no administrada.

access
FileAccess

Modo de acceso a archivos para la secuencia de memoria no administrada.

Se aplica a