从c ++ / cx转换为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();
}

我收到以下错误

错误(活动)E0312不存在从“ winrt :: impl :: com_refwinrt :: hstring”到“ wchar_t *”的合适的用户定义转换

我希望通过try_as获得winrt :: hstring,并且可以从中获取.c_str(),但是我却获得了winrt :: impl :: com_refwinrt :: hstring。我想念什么?

解决方法

您似乎要取消对IInspectable界面后面的标量值的装箱(请参见Boxing and unboxing scalar values to IInspectable with C++/WinRT)。要取消装箱,您需要使用unbox_value功能模板:

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

尽管存在疑问,但是您是否真的要返回一个指向其他地方拥有的某些数据中间的指针。最好只按值返回hstringString handling in C++/WinRT拥有关于该主题的更多信息。