CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Threaded View

  1. #1
    Join Date
    Mar 2006
    Posts
    151

    safe to reinterpret_cast vector<CComPtr<>>?

    Hello,

    I am trying to use CComPtr to manage all of the COM objects in a block of code which uses DirectWrite.

    IDWriteFontFace::GetFiles takes an array of pointers to IDWriteFontFile as its second argument. The caller must supply the memory block which will receive the pointers. I want to use std::vector<CComPtr> to manage all of the returned IDWriteFontFile objects. Can I do that as shown in the following code snippet?

    Please note that I'm using static_assert to verify that the memory layout of CComPtr is what I expect. Then reinterpret_cast is used to give GetFiles the pointer type it expects, and that pointer type is what I would effectively expect the guts of the vector object to be.

    The code is post C++11 so CAdapt isn't needed.

    Is this safe and guaranteed to work? If not, is there an alternative method I could use which is better than reverting to raw pointers?


    Code:
                // Query the number of files.
                UINT32 nFiles = 0;
                ThrowIfFailed(ptrFontFace->GetFiles(&nFiles, nullptr));
    
    
                // Allocate storage to hold the files.
                static_assert(sizeof(CComPtr<IDWriteFontFile>) == sizeof(IDWriteFontFile*),
                              "The vector of CComPtr which follows cannot be used safely.");
                std::vector<CComPtr<IDWriteFontFile>> vFontFiles;
                vFontFiles.resize(nFiles);
    
    
                // Retreive the files into the allocated storage.
                ThrowIfFailed(ptrFontFace->GetFiles(&nFiles, reinterpret_cast<IDWriteFontFile**>(vFontFiles.data())));
    Thank you,
    GeoRanger
    Last edited by GeoRanger; January 30th, 2020 at 12:05 AM. Reason: Asked for an alternative idea if the snippet is not safe and guaranteed to work

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured