做了包装类的COM互操作的IStream已经存在?存在、操作、COM、IStream

2023-09-02 10:38:03 作者:森

我要写一个包装COM互操作的IStream使得code,它需要一个标准的.NET流可以使用它。

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.

请注意我遇到code实现的IStream包装一个.NET流,但我需要相反的。

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

推荐答案

它做,System.Runtime.InteropServices.ComTypes.IStream.一个样品包装:

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