C++ COM ATL DLL

C++ COM ATL DLL

本文关键字:DLL ATL COM C++      更新时间:2023-10-16

我是visual studio 2012 pro,使用v110_xp工具集。我想在COM类中"转换"我的c++动态库。库的结构是这样的:

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 */ );

现在,所有的方法和函数都可以抛出一个从std::exception派生的类(析构函数除外)。

我想让它成为一个COM类,这样我就可以从C#中使用它。实现这一点最快捷的方法是什么?ATL有帮助吗?有人知道一些教程或书籍吗。我在COM中没有经验。

您至少应该从IUnknown派生类。如果您要在某些脚本中使用COM,那么您可以从IDispatch派生类。COM的一本好书是Jonathan Bates的《用ATL创建轻量级组件》。

但是,一些真正初级的实现可能是这样的:

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_;
};