首页 > 解决方案 > 如何在 C++/winrt 中调用 StorageFile.OpenReadAsync?

问题描述

在我继续努力在 C++/winrt 中加载 .svg 文件的集合时,我遇到了一个神秘的链接错误。我想尝试使用 CanvasSvgDocument.ReadAsync(resourceCreator, filestream)。要到达那里,首先需要从 StorageFile 获取流,这似乎是实现它的方法(nextFile,一个 StorageFile,在本示例中已加载)。这当然是在定义为 IAsyncAction 的方法中。我将从文件顶部列出#includes 和命名空间。

#include "winrt/Windows.ApplicationModel.h"
#include "winrt/Windows.Storage.h"
#include "winrt/Windows.Storage.Streams.h"
#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/Windows.Storage.Search.h"
#include "winrt/Windows.UI.Core.h"
#include "winrt/Windows.UI.Xaml.Media.h"
#include "pch.h"

using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Storage;
using namespace Windows::Storage::Provider;
using namespace Windows::Storage::Search;
using namespace Windows::Storage::Streams;

这是有问题的调用:

IRandomAccessStreamWithContentType fileStream = co_await nextFile.OpenReadAsync();

这会产生一个链接错误,我将在下面输入。我是否尝试使用 fileStream 结果的完全限定名称并不重要:

winrt::Windows::Storage::Streams::IRandomAccessStreamWithContentType fileStream = co_await nextFile.OpenReadAsync();

无论哪种方式,我都会收到此链接错误:

错误 LNK2019 无法解析外部符号“public: struct winrt::Windows::Foundation::IAsyncOperation __thiscall winrt::impl::consume_Windows_Storage_Streams_IRandomAccessStreamReference::OpenReadAsync(void)const” (?OpenReadAsync@?$consume_Windows_Storage_Streams_IRandomAccessStreamReference@UIStorageFile@Storage@Windows@winrt @@@impl@winrt@@QBE?AU?$IAsyncOperation@UIRandomAccessStreamWithContentType@Streams@Storage@Windows@winrt@@@Foundation@Windows@3@XZ) 在函数“public: struct winrt::Windows::Foundation: :IAsyncAction __thiscall AppEngine::ResourceManager::LoadSvgResources$_ResumeCoro$2(struct winrt::Microsoft::Graphics::Canvas::UI::Xaml::CanvasControl)"(?LoadSvgResources$_ResumeCoro$2@ResourceManager@AppEngine@@QAE?AUIAsyncAction@Foundation@Windows@winrt@@UCanvasControl@Xaml@UI@Canvas@Graphics@Microsoft@6@@Z)

我也尝试过使用 auto 作为结果类型,但没有运气。在 C++/winrt 中使用 OpenReadAsync() 获取流的正确方法是什么?

标签: c++-winrtwin2d

解决方案


您显然是在启用预编译头文件的情况下进行编译(由#include "pch.h"指令提示)。这样做时,用于生成预编译头的头必须包含在使用它的编译单元的第一个非空、非注释行中。

/ Yu (Use Precompiled Header File)文档有相关信息:

编译器将 .h 文件之前出现的所有代码视为预编译。它跳到与 .h 文件关联的 #include 指令之外,使用 .pch 文件中包含的代码,然后编译 .h 文件之后的所有代码filename

换句话说,#include "pch.h"指令之前的所有包含都将被忽略。由于 C++/WinRT 是一个只有标头的库,这最终会导致链接器错误。

解决问题

  • #include "pch.h"指令移动到文件的最顶部,或
  • #include指令替换为相关编译单元上的/FI(命名强制包含文件)编译器选项,或
  • 禁用预编译头文件的使用。

推荐阅读