从 c++/cx 转换为 c++/winrt 时与 winrt::impl::com_ref<winrt::hstring> 相关的错误

error related to winrt::impl::com_ref<winrt::hstring> when converting from c++/cx to c++/winrt

在cppcx中,我曾经有过这个:

auto button = safe_cast<ContentControl ^>(obj);
if (auto text = dynamic_cast<Platform::String^>(button->Content)) {
    return text->Data();
}

当我尝试将此代码转换为 cppwinrt 时:

auto button = obj.as<winrt::ContentControl>();
if (auto text = button.Content().try_as<winrt::hstring>()) {
    return text.c_str();
}

我收到以下错误:

Error (active) E0312 no suitable user-defined conversion from "winrt::impl::com_refwinrt::hstring" to "wchar_t*" exists

我希望我能得到 winrt::hstring 作为 try_as 的结果,我可以从中得到 .c_str() ,但我得到了一个 winrt: :impl::com_refwinrt::hstring 代替。我错过了什么?

您似乎想拆箱 IInspectable 接口后面的标量值(参见 Boxing and unboxing scalar values to IInspectable with C++/WinRT). For unboxing you'll want to use the unbox_value 函数模板:

auto button = obj.as<winrt::ContentControl>();
if (auto text = unbox_value<winrt::hstring>(button.Content())) {
    return text.c_str();
}

虽然值得怀疑,但您是否真的想要 return 一个指向其他地方拥有的某些数据的中间的指针。最好只是 return 一个 hstring by value. String handling in C++/WinRT 有关于这个主题的更多信息。