Domanda

class Foo
{
   static bool Bar(Stream^ stream);
};

class FooWrapper
{
   bool Bar(LPCWSTR szUnicodeString)
   {
       return Foo::Bar(??);
   }
};

MemoryStream avrà byte[] ma mi piacerebbe come per fare questo, senza copiare i dati, se possibile.

È stato utile?

Soluzione

È possibile evitare la copia se si utilizza un UnmanagedMemoryStream() invece (classe esiste .NET FCL 2.0 e versioni successive).Come MemoryStream, è una sottoclasse di IO.Stream, e ha tutti i soliti flusso di operazioni.

Microsoft descrizione della classe è:

Fornisce l'accesso al codice di blocchi di memoria da codice gestito.

che praticamente ti dice che cosa avete bisogno di sapere.Nota che UnmanagedMemoryStream() non è compatibile con CLS.

Altri suggerimenti

Se ho dovuto copiare la memoria, credo che il seguente lavoro:


static Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)
{
   //validate the input parameter
   if (szUnicodeString == NULL)
   {
      return nullptr;
   }

   //get the length of the string
   size_t lengthInWChars = wcslen(szUnicodeString);  
   size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);

   //allocate the .Net byte array
   array^ byteArray = gcnew array(lengthInBytes);

   //copy the unmanaged memory into the byte array
   Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);

   //create a memory stream from the byte array
   return gcnew MemoryStream(byteArray);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top