Channels ▼
RSS

C/C++

Using C++ and COM with WinRT


To implement the necessary plumbing, I will create two template classes. The first class Vector<T> will implement IVector<T> and IIterable<T> using a std::vector<T>. The second class Iterator<T> will implement IIterator<T> using the std::vector<T>::iterator iterator. Theses template classes are exposed as WinRT classes by inheriting from RuntimeClass<T>. Here is the source code:

template <class T>
class Iterator : public RuntimeClass<IIterator<T>>
{
    InspectableClass(L"Library1.Iterator", BaseTrust)

private:
    typedef typename std::shared_ptr<std::vector<T>> V;
    typedef typename std::vector<T>::iterator IT;

public:
    Iterator() {}

    HRESULT Init(const V & item)
    {
        _v = item;
        _it = _v->begin();
        if (_it != _v->end())
        {
            _element = *_it;
            _bElement = TRUE;
        }
        else
            _bElement = FALSE;
        return S_OK;
    }

public:
    virtual HRESULT STDMETHODCALLTYPE get_Current(T *current)
    {
        if (_it != _v->end())
        {
            _bElement = TRUE;
            _element = *_it;
            *current = _element;
        }
        else
        {
            _bElement = FALSE;
        }
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE get_HasCurrent(boolean *hasCurrent)
    {
        if (_bElement)
            *hasCurrent = TRUE;
        else
            *hasCurrent = FALSE;
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE MoveNext(boolean *hasCurrent)
    {
        if (_it != _v->end())
        {
            ++_it;
            if (_it == _v->end())
                *hasCurrent = FALSE;
            else
                *hasCurrent = TRUE;
        }
        else
        {
            *hasCurrent = FALSE;
        }
        return S_OK;
    }

private:
    V _v;
    IT _it;
    T _element;
    boolean _bElement = FALSE;
};

template <typename T>
class Vector : public RuntimeClass<IVector<T>, IIterable<T>>
{
    InspectableClass(L"Library1.Vector", BaseTrust)

public:
    Vector() 
    {
        std::shared_ptr<std::vector<T>> ptr(new std::vector<T>());
        _v = ptr;
    }

public:

    // read methods
    virtual HRESULT STDMETHODCALLTYPE GetAt(unsigned index, T *item)
    {
        *item = (*_v)[index];
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE get_Size(unsigned *size)
    {
        *size = _v->size();
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE GetView(IVectorView<T> **view)
    {
        return E_NOTIMPL;
    }

    virtual HRESULT STDMETHODCALLTYPE IndexOf(T value, unsigned *index, boolean *found)
    {
        unsigned foundedIndex = 0;
        bool founded = false;
        for (std::vector<T>::const_iterator it = _v->cbegin() ; it != _v->end() ; ++it)
        {
            const T & v = *it;
            if (v == value)
            {
                founded = true;
                break;
            }
            foundedIndex++;
        }
        if (founded == true)
        {
            *found = TRUE;
            *index = foundedIndex;
        }
        else
        {
            *found = FALSE;
        }
        return S_OK;
    }

    // write methods
    virtual HRESULT STDMETHODCALLTYPE SetAt(unsigned index, T item)
    {
        if (index < _v->size())
        {
            (*_v)[index] = item;
        }
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE InsertAt(unsigned index, T item)
    {
        _v->emplace(_v->begin() + index, item);
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE RemoveAt(unsigned index)
    {
        if (index < _v->size())
        {
            _v->erase(_v->begin() + index);
        }
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE Append(T item)
    {
        _v->emplace_back(item);
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE RemoveAtEnd()
    {
        if (!_v->empty())
        {
            _v->pop_back();
        }
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE Clear()
    {
        _v->clear();
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE First(IIterator<T> **first)
    {
        ComPtr<Iterator<T>> p = Make<Iterator<T>>();
        p->Init(_v);
        *first = p.Detach();
        return S_OK;
    }

private:
    std::shared_ptr<std::vector<T>> _v;
};

You will notice that access to the std::vector<T> can be enhanced and better protected.

Now that we have the plumbing to deal with collections, let's use it in a WinRT component with two methods. The first method returns a vector of strings, and the second method returns a vector of integers. Here is the IDL file:


    [uuid(3EC4B4D6-14A6-4D0D-BB96-31DA25224A16), version(COMPONENT_VERSION)]
    interface IRoot : IInspectable
    {
        HRESULT GetVector([out][retval] Windows.Foundation.Collections.IVector<HSTRING>** value);
        HRESULT GetVectorInt([out][retval] Windows.Foundation.Collections.IVector<int>** value);
    }

    [version(COMPONENT_VERSION), activatable(COMPONENT_VERSION)]
    runtimeclass Root
    {
        [default] interface IRoot;
    }

Here is the C++ class header that implements the IRoot interface:

namespace ABI
{
    namespace Library1
    {
        class Root : public RuntimeClass<IRoot>
        {
            InspectableClass(L"Library1.Root", BaseTrust)

        public:
            Root() {}

        public:
            STDMETHOD(GetVector)(IVector<HSTRING>** value);
            STDMETHOD(GetVectorInt)(IVector<int>** value);
        };

        ActivatableClass(Root);
    }
}

Here are the two methods of the Root C++ class:

namespace ABI
{
    namespace Library1
    {
        STDMETHODIMP Root::GetVector(IVector<HSTRING>** value)
        {
            ComPtr<Vector<HSTRING>> v = Make<Vector<HSTRING>>();
            HString str;
            str.Set(L"String1");
            v->Append(str.Detach());
            str.Set(L"String2");
            v->Append(str.Detach());
            str.Set(L"String3");
            v->Append(str.Detach());
            str.Set(L"String4");
            v->Append(str.Detach());
            *value = v.Detach();
            return S_OK;
        }

        STDMETHODIMP Root::GetVectorInt(IVector<int>** value)
        {
            ComPtr<Vector<int>> v = Make<Vector<int>>();
            v->Append(10);
            v->Append(20);
            v->Append(30);
            v->Append(40);
            *value = v.Detach();
            return S_OK;
        }
    }
}

The Vector<T> template class is used in both methods. To create a WinRT class, you need to wrap your component in a ComPtr<T> object and use the Make<T> function. You can also see the use of the HString class to handle the new HSTRING Windows type.

The complete source code for this article is available as a working sample in the Microsoft Dev Center: Windows Store apps.


Christophe Pichaud is a software engineer from Paris, France. He works for Sogeti and uses C++ and C#.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video