2010-04-06 26 views
19

Tôi sắp viết Trình bao bọc cho một IStream liên kết COM sao cho mã mong đợi một Dòng tiêu chuẩn .NET có thể sử dụng nó.Lớp trình bao bọc cho IStream COM interop đã tồn tại chưa?

Tuy nhiên nó xảy ra với tôi rằng loại điều này có thể đã được thực hiện trước đó (mặc dù tôi đã không thể tìm thấy nó bản thân mình với tìm kiếm web).

Vì vậy, tôi chỉ đưa nó ra đây trong trường hợp tôi sắp sửa phát minh lại bánh xe.

Lưu ý: Tôi đã bắt gặp mã triển khai IStream gói một luồng .NET nhưng tôi cần ngược lại.

Trả lời

33

Nó có, System.Runtime.InteropServices.ComTypes.IStream. Trình bao bọc mẫu:

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

Cảm ơn, đó là khởi đầu tuyệt vời cho 10. – AnthonyWJones

+0

Cảm ơn bạn đã làm điều này. Một câu trả lời thực sự hữu ích. –

+0

Làm cách nào để tôi thực hiện 'Vị trí'? Người tiêu dùng luồng của tôi cần nó. –

Các vấn đề liên quan