Question

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

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

MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.

Was it helpful?

Solution

You can avoid the copy if you use an UnmanagedMemoryStream() instead (class exists in .NET FCL 2.0 and later). Like MemoryStream, it is a subclass of IO.Stream, and has all the usual stream operations.

Microsoft's description of the class is:

Provides access to unmanaged blocks of memory from managed code.

which pretty much tells you what you need to know. Note that UnmanagedMemoryStream() is not CLS-compliant.

OTHER TIPS

If I had to copy the memory, I think the following would work:


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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top