C ++ COM ATL DLL

时间:2013-06-24 15:34:30

标签: c++ com atl

我是使用v110_xp工具集的visual studio 2012 pro。我想在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中没有经验。

1 个答案:

答案 0 :(得分:1)

你至少应该从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_;
};
相关问题