Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c# - Does a wrapper class for a COM interop IStream already exist?

I'm about to write a Wrapper for a COM interop IStream so that code that expects a standard .NET Stream can use it.

However it occurs to me that this sort of thing may already have been done before (although I haven't been able to find it myself with web searching).

So I'm just putting this out here in case I'm about to re-invent the wheel.

Note I've come across code implementing IStream wrapping a .NET stream but I need the reverse.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It does, System.Runtime.InteropServices.ComTypes.IStream. A sample wrapper:

using System;
using iop = System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;

public class ComStreamWrapper : System.IO.Stream {
  private IStream mSource;
  private IntPtr mInt64;

  public ComStreamWrapper(IStream source) { 
    mSource = source;
    mInt64 = iop.Marshal.AllocCoTaskMem(8);
  }

  ~ComStreamWrapper() { 
    iop.Marshal.FreeCoTaskMem(mInt64); 
  }

  public override bool CanRead { get { return true; } }
  public override bool CanSeek { get { return true; } }
  public override bool CanWrite { get { return true; } }

  public override void Flush() { 
    mSource.Commit(0); 
  }

  public override long Length { 
    get { 
      STATSTG stat;
      mSource.Stat(out stat, 1);
      return stat.cbSize;
    }
  }

  public override long Position {
    get { throw new NotImplementedException(); }
    set { throw new NotImplementedException(); }
  }

  public override int Read(byte[] buffer, int offset, int count) {
    if (offset != 0) throw new NotImplementedException();
    mSource.Read(buffer, count, mInt64);
    return iop.Marshal.ReadInt32(mInt64);
  }

  public override long Seek(long offset, System.IO.SeekOrigin origin) {
    mSource.Seek(offset, (int)origin, mInt64);
    return iop.Marshal.ReadInt64(mInt64);
  }

  public override void SetLength(long value) {
    mSource.SetSize(value);
  }

  public override void Write(byte[] buffer, int offset, int count) {
    if (offset != 0) throw new NotImplementedException();
    mSource.Write(buffer, count, IntPtr.Zero);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...