In cppcx, I used to have this:
auto button = safe_cast<ContentControl ^>(obj);
if (auto text = dynamic_cast<Platform::String^>(button->Content)) {
return text->Data();
}
When I try to do this to convert this code to cppwinrt:
auto button = obj.as<winrt::ContentControl>();
if (auto text = button.Content().try_as<winrt::hstring>()) {
return text.c_str();
}
I get the following error:
Error (active) E0312 no suitable user-defined conversion from "winrt::impl::com_refwinrt::hstring" to "wchar_t*" exists
I was hoping I would get a winrt::hstring as a result of the try_as and I can get the .c_str() from it, but I am getting a winrt::impl::com_refwinrt::hstring instead. What am I missing?
It looks like you want to unbox a scalar value behind an IInspectable
interface (see Boxing and unboxing scalar values to IInspectable with C++/WinRT). For unboxing you'll want to use the unbox_value function template:
auto button = obj.as<winrt::ContentControl>();
if (auto text = unbox_value<winrt::hstring>(button.Content())) {
return text.c_str();
}
Although it's questionable, whether you really want to return a pointer that points into the middle of some data owned elsewhere. It's probably best to just return an hstring
by value. String handling in C++/WinRT has more information on the topic.