Search code examples
.netc++interopmanaged-c++

How do I convert an IntPtr to a Stream?


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.


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.