gpt4 book ai didi

c# - 如何在 C# 中实现 IRandomAccessStream?

转载 作者:太空狗 更新时间:2023-10-29 20:28:05 27 4
gpt4 key购买 nike

我想在 C# 中实现 IRandomAccessStream 的实例(它将返回实时生成的数据)。流实际上不需要可写或可查找,但我想在 ReadAsync 方法(实际上是 IInputStream 的一部分)中返回我自己的数据。

public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
{
throw new NotImplementedException("To be done");
}

我的两个主要问题是:

  1. 如何返回实现 IAsyncOperationWithProgress 的内容?框架中是否内置了任何东西来帮助解决这个问题?
  2. 如何将数据写入缓冲区? IBuffer 只有 LengthCapacity 属性(具体的 Buffer 类也不再提供)。

最佳答案

How to Convert byte Array to IRandomAccessStream

我找到了这篇博客文章,希望IRandomAccessStream 的实现可以成为您的起点。

class MemoryRandomAccessStream : IRandomAccessStream
{
private Stream m_InternalStream;

public MemoryRandomAccessStream(Stream stream)
{
this.m_InternalStream = stream;
}

public MemoryRandomAccessStream(byte[] bytes)
{
this.m_InternalStream = new MemoryStream(bytes);
}

public IInputStream GetInputStreamAt(ulong position)
{
this.m_InternalStream.Seek((long)position, SeekOrigin.Begin);

return this.m_InternalStream.AsInputStream();
}

public IOutputStream GetOutputStreamAt(ulong position)
{
this.m_InternalStream.Seek((long)position, SeekOrigin.Begin);

return this.m_InternalStream.AsOutputStream();
}

public ulong Size
{
get { return (ulong)this.m_InternalStream.Length; }
set { this.m_InternalStream.SetLength((long)value); }
}

public bool CanRead
{
get { return true; }
}

public bool CanWrite
{
get { return true; }
}

public IRandomAccessStream CloneStream()
{
throw new NotSupportedException();
}

public ulong Position
{
get { return (ulong)this.m_InternalStream.Position; }
}

public void Seek(ulong position)
{
this.m_InternalStream.Seek((long)position, 0);
}

public void Dispose()
{
this.m_InternalStream.Dispose();
}

public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
{
var inputStream = this.GetInputStreamAt(0);
return inputStream.ReadAsync(buffer, count, options);
}

public Windows.Foundation.IAsyncOperation<bool> FlushAsync()
{
var outputStream = this.GetOutputStreamAt(0);
return outputStream.FlushAsync();
}

public Windows.Foundation.IAsyncOperationWithProgress<uint, uint> WriteAsync(IBuffer buffer)
{
var outputStream = this.GetOutputStreamAt(0);
return outputStream.WriteAsync(buffer);
}
}

关于c# - 如何在 C# 中实现 IRandomAccessStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13723354/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com