Search code examples
c++arraysc++-winrt

Array as value in ValueSet


My goal is to add array of strings as value into ValueSet. I can do it in C# without any problem, but facing some problems in C++-WinRT.

I am trying to pass array_view to box_value in order to convert it to IInspectable type, but getting error T must be WinRT type. Here is sample code to check the problem:

ValueSet MyValueSet;
hstring key(L"key");
vector<wstring> mystringvalues{ L"1",L"2" };
std::vector<hstring> hvector;
for (std::wstring v : mystringvalues) {
    hvector.push_back(hstring(v));
}
array_view<hstring> hvalue(hvector);
IInspectable keyValue = box_value(hvalue);
MyValueSet.Insert(key, keyValue);

Please advise how can I achieve this.


Solution

  • See https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/collections on how to create Collection objects.

    This code should work:

    ValueSet myValueSet;
    hstring key(L"key");
    std::vector<std::wstring> mystringvalues{ L"1",L"2" };
    std::vector<hstring> hvector;
    for (std::wstring v : mystringvalues) {
        hvector.push_back(hstring(v));
    }
    myValueSet.Insert(key, winrt::single_threaded_vector(std::move(hvector)));
    

    or even shorter:

    ValueSet myValueSet;
    myValueSet.Insert(L"key", winrt::single_threaded_vector<hstring>({L"1", L"2"}));