【问题标题】:Does a wrapper class for a COM interop IStream already exist?COM 互操作 IStream 的包装类是否已经存在?
【发布时间】:2011-02-04 21:10:19
【问题描述】:

我即将为 COM 互操作 IStream 编写一个 Wrapper,以便需要标准 .NET Stream 的代码可以使用它。

但是我突然想到,这种事情以前可能已经做过(尽管我自己无法通过网络搜索找到它)。

所以我把它放在这里,以防我要重新发明轮子。

请注意,我遇到了实现包装 .NET 流的 IStream 的代码,但我需要反过来。

【问题讨论】:

    标签: c# .net .net-3.5


    【解决方案1】:

    确实如此,System.Runtime.InteropServices.ComTypes.IStream。一个示例包装器:

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

    【讨论】:

    • 谢谢,这是 10 的一个很好的开端。
    • 谢谢。一个非常有用的答案。
    • 我将如何实施Position?我的流的消费者需要它。
    • 我想通了,Read() 需要设置Position += count,Seek() 需要设置Position = offset + (int) origin
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2012-02-27
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多