Elvis Dukaj
Elvis Dukaj

Reputation: 7368

C++ COM ATL DLL

I am visual studio 2012 pro with v110_xp toolset. I want to "transform" my c++ dynamic library in a COM class. The library is structured in this way:

struct A;
struct B;

class IClass {
public:
    virtual ~IClass() = 0;
    virtual A doA() = 0;
    virtual B doB() = 0;
    virtual void getA( A& a ) = 0;
    virtual void getB( B& b) = 0;
};
inline IClass::~IClass() {}

typedef std::unique_ptr< IClass > IClassPtr;
API_LIB IClassPtr ClassCreate( /* param */ );

Now all the method and funcion can throw a class deriving from std::exception ( with the exception of the destructor).

I want make this a COM class so I can use it from C#. Which is the fastes way to accomplish this? Can ATL help? Does someone know some tutorial or books. I've no expirience in COM.

Upvotes: 0

Views: 947

Answers (1)

user1764961
user1764961

Reputation: 693

You should at least derive your class from IUnknown. If you are about to use your COM in some scripting, then you would derive your class from IDispatch. A good book for COM is Creating Lightweight Components with ATL by Jonathan Bates.

But, some really rudimentary implementation could look like this:

class MyCOM : public IUnknown
{
public:
    static MyCOM * CreateInstance()
    {
        MyCOM * p( new(std::nothrow) MyCOM() );
        p->AddRef();
        return p;
    }

    ULONG __stdcall AddRef()
    {
        return ++nRefCount_;
    }

    ULONG __stdcall Release()
    {
        assert( nRefCount_ > 0 );

        if( --nRefCount_ == 0 )
        {
            delete this;
            return 0;
        }

        return nRefCount_;
    }

    HRESULT __stdcall QueryInterface( const IID & riid, void** ppvObject )
    {
        if( riid == IID_IUnknown )
        {
            AddRef();
            *ppvObject = this;
            return S_OK;
        }

        // TO DO: add code for interfaces that you support...

        return E_NOINTERFACE;
    }

private:

    MyCOM()
    : nRefCount_( 0 ){}
    MyCOM(const MyCOM & ); // don't implement
    MyCOM & operator=(const MyCOM & ); // don't implement
    ~MyCOM(){}

    ULONG nRefCount_;
};

Upvotes: 1

Related Questions