Ben Stevens
Ben Stevens

Reputation: 35

How to return an array asyc, writing a Windows Runtime Component in C++/WinRT

What is the best way to asynchronously return an array from a Windows Runtime Component written in C++/WinRT, given that IAsyncOperation<TResult> is not allowed as a return type if TResult is an array?

It's possible to wrap an array inside a PropertyValue, but both boxing and unboxing the array creates copies, which seems inefficient. At the moment, what I'm doing is writing a custom component to store the com_array (which has a constructor that allows me to move in the com_array), with a DetachArray function that moves the array on return to the caller. Is this the best way - it seems a little complicated? Also, in this case, if I am calling the DetachArray function from C#, is the array copied or not? I don't know how the interaction between managed and unmanaged memory works. I assume that the use of com_array as opposed to std::vector has something to do with this.

Upvotes: 1

Views: 526

Answers (1)

Faywang - MSFT
Faywang - MSFT

Reputation: 5868

The TResult of IAsyncOperation needs to be passed is a Windows Runtime type. If you want to return an array, you could try to use Windows::Foundation::Collections::IVector as a collection object instead of winrt::com_array. In that case, it will be convenient and doesn't need to box or unbox. For example:

Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVector<hstring>> Class::MyMethod()
{
    Windows::Foundation::Collections::IVector<hstring> coll1{ winrt::single_threaded_vector<hstring>() };
    ......
    co_return coll1;
}

Upvotes: 3

Related Questions