COM 嵌套类实现COM

Ia.h
//#include <objbase.h>
//#include <unknwn.h>
interface IA:public IUnknown
{
	virtual int _stdcall Add(int a,int b)=0;
};
// {B7691C47-7C3A-419c-894D-9B428A92A0D8}
const IID IID_IA = 
{ 0xb7691c47, 0x7c3a, 0x419c, { 0x89, 0x4d, 0x9b, 0x42, 0x8a, 0x92, 0xa0, 0xd8 } };

 

Ib.h
//#include <objbase.h>
//#include <unknwn.h>
interface IB:public IUnknown
{
	virtual HRESULT _stdcall Pass(int a,int b,int* c)=0;
};
// {3C2BC1A6-6F46-4b09-8FAB-8A18C6F4FACA}
const IID IID_IB = 
{ 0x3c2bc1a6, 0x6f46, 0x4b09, { 0x8f, 0xab, 0x8a, 0x18, 0xc6, 0xf4, 0xfa, 0xca } };

 

Co.cpp
#include "ia.h"
#include "ib.h"
#include <atlbase.h>
class CO:public IUnknown
{
public:
	CO();
	HRESULT _stdcall QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject);
	ULONG _stdcall AddRef();
	ULONG _stdcall Release();
	class CA:public IA
	{
	public:
		CO* m_parent;
		HRESULT _stdcall QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject);
		ULONG _stdcall AddRef();
		ULONG _stdcall Release();
		int _stdcall Add(int a,int b);
	} ca;
	class CB:public IB
	{
	public:
		CO* m_parent;
		HRESULT _stdcall QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject);
		ULONG _stdcall AddRef();
		ULONG _stdcall Release();
		HRESULT _stdcall Pass(int a,int b,int* c);
	} cb;
private:
	long m_ref;
};
CO::CO()
{
	m_ref=0;
	ca.m_parent=this;
	cb.m_parent=this;
}
HRESULT _stdcall CO::QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject)
{
	if(riid==IID_IA)
	{
		*ppvObject=(IA*)(&ca);
	}
	else if(riid==IID_IB)
	{
		*ppvObject=(IB*)(&cb);
	}
	else if(riid==IID_IUnknown)
	{
		*ppvObject=(IUnknown*)(this);
	}
	else
	{
		*ppvObject=NULL;
		return E_NOINTERFACE;
	}
	reinterpret_cast<IUnknown*>(*ppvObject)->AddRef();
	return S_OK;
}
ULONG _stdcall CO::AddRef()
{
	++m_ref;
	return m_ref;
}
ULONG _stdcall CO::Release()
{
	--m_ref;
	if(m_ref==0)
	{
		delete this;
		return 0;
	}
	return m_ref;
}
HRESULT _stdcall CO::CA::QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject)
{
	return m_parent->QueryInterface(riid,ppvObject);
}
ULONG _stdcall CO::CA::AddRef()
{
	return m_parent->AddRef();
}
ULONG _stdcall CO::CA::Release()
{
	return m_parent->Release();
}
int _stdcall CO::CA::Add(int a,int b)
{
	int x=a+b;
	return x;
}
HRESULT _stdcall CO::CB::QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject)
{
	return m_parent->QueryInterface(riid,ppvObject);
}
ULONG _stdcall CO::CB::AddRef()
{
	return m_parent->AddRef();
}
ULONG _stdcall CO::CB::Release()
{
	return m_parent->Release();
}
HRESULT _stdcall CO::CB::Pass(int a,int b,int* c)
{
	int x=a-b;
	c=&x;
	return S_OK;
}
IUnknown* CreateInterface()
{
	IUnknown* pc=static_cast<IUnknown*>(new CO);
	return pc;
}

 

你可能感兴趣的:(C++,c,C#)