【问题标题】:Wrap Windows 8/WP8 StorageFile for synchronous C++ access包装 Windows 8/WP8 StorageFile 以实现同步 C++ 访问
【发布时间】:2014-09-23 17:07:34
【问题描述】:

我需要一个 C++ 包装类,它可以从 Windows 8/WP8 存储文件 (http://msdn.microsoft.com/library/windows/apps/br227171) 同步读取/写入/查找数据:

class FileWrapper
{
public:
    FileWrapper(StorageFile^ file); // IRandomAccessStream or IInputStream 
                                    // are fine as input arguments too

    byte* readBytes(int bytesToRead, int &bytesGot);
    bool writeBytes(byte* data, int size);
    bool seek(int position);
}

应该从文件中即时读取数据。不应将其缓存在内存中,也不应将存储文件复制到应用程序的目录中,以便使用标准 fopen 和 ifstream 函数访问它。

我试图弄清楚如何做到这一点(包括 Microsoft 文件访问示例代码:http://code.msdn.microsoft.com/windowsapps/File-access-sample-d723e597),但我被每个操作的异步访问所困扰。有人暗示如何实现这一目标吗?还是有内置功能?

问候,

【问题讨论】:

    标签: c++ windows-phone-8 windows-runtime ifstream storagefile


    【解决方案1】:

    通常,您使用 create_task() 方法包装异步操作,您可以通过调用 task.get() 来等待任务执行完成以实现同步,但是 IIRC 这不适用于文件访问,因为操作可能会尝试返回执行它们的同一线程,如果您阻塞该线程 - 您最终会陷入死锁。我没有时间尝试这个,但也许如果你从另一个线程开始 - 你可以像这样在你的线程上等待完成,尽管它可能仍然死锁:

    auto createTaskTask = create_task([]()
    {
        return create_task(FileIO::ReadTextAsync(file));
    }
    
    auto readFileTask = createTaskTask.get();
    
    try 
    { 
        String^ fileContent = readFileTask.get(); 
    } 
    catch(Exception^ ex) 
    { 
        ...
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      相关资源
      最近更新 更多