How to use ComPtr in C++Builder?

90 views Asked by At

I'm trying to implement DX11 in my C++Builder project. All SDK references use the ComPtr<> template, eg:

// Create the DX11 API device object, and get a corresponding context.
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;

Of course, C++Builder doesn't know ComPtr, so how can I include it, or port over the ComPtr template? Basically, get it to work in C++Builder.

UPDATE

So, someone asked me about the headers. Obviously, I don't have the needed header, hence I'm asking here for a solution.

#include <vcl.h>
#include <winuser.h>
#include <d2d1.h>
#include <d3d11.h>

According to Microsoft, I should include <client.h>, but that one can't be found by C++Builder.

2

There are 2 answers

1
SmellyCat On

ATL::CComPtr is a Microsoft class. I believe that it's in Microsoft's atlcom.h or atlcomcli.h. There will be an MFC equivalent.

If you don't have Visual Studio, the template will be like:

template<typename T>
class CComPtr
{
    T *m_pObj;
public:
    CComPtr() : m_pObj(nullptr) {}
    CComPtr(T *p) : m_pObj(p)
    {
        p->AddRef();
    }
    ~CComPtr();

    HRESULT CreateInstance(REFCLSID rclsid, DWORD dwClsContext, LPUNKNOWN pUnkOuter=nullptr, REFIID    riid = IID_IUnknown)
    {
        ASSERTE(m_pObj == nullptr); // if not, release first
        return CoCreateInstance(rclsid, pUnkOuter, dwClasContext, riid, &m_pObj);
    }

    void Release()
    {
        if (m_pObj)
            m_pObj->Release();
        m_pObj = nullptr;
    }

    // These methods access the pointer without adding or releasing references.
    void Attach(T *p);
    T* Detach();

    // non-modifying operator overloads
    T* operator *();
    T* operator ->();
    operator bool();
    // modifying overload - Pointer should be null before use.
    T** operator &();
};
0
Remy Lebeau On

C++Builder has its own smart-interface-pointer classes, such as TComInterface in <utilcls.h>:

#include <utilcls.h>

TComInterface<ID3D11Device> device;
TComInterface<ID3D11DeviceContext> context;