Getting a COM Object from a Control
I am writing a Control (MyCOMControl) which acts as a front-end for a COM Object (MyCOMObject), that is - MyCOMControl has a few buttons which when pressed call methods on MyCOMObject. But I want the client to be able to call some of those methods directly, for example in VB it would be:
myControl.GetMyObject.DoSomething
However the client should not be able to create a MyCOMObject ie a VB Client should not be able to:
Dim myObj As New MyCOMObject
I have implemented this as shown below but when I run the following VB code:
Dim myObj As MyCOMObject
Dim test As String
Set myObj = myControl.GetMyObject
test = myObj.DoSomething
The last line causes a "Object variable or With block variable not set" error and myObj is "Nothing". What am I missing?
So what I have so far is:
//MyCOMObject interface
[
object,
uuid(D184560F-D9DB-4EB8-815F-FAC17C443116),
dual,
nonextensible,
helpstring("IMyCOMObject Interface"),
pointer_default(unique)
]
interface IMyCOMObject : IDispatch{
[id(1), helpstring("Do Something")] HRESULT DoSomething([out, retval]BSTR* pAnswer);
//Other methods here
};
//MyCOMControl Interface
[object,
uuid(4BED3339-6DDE-4EB7-BC0B-2B7908855543),
dual,
nonextensible,
helpstring("IMyCOMControl Interface"),
pointer_default(unique)
]
interface IMyCOMControl : IDispatch{
//Other methods and properties here ...
[id(15), helpstring("Get the object")] HRESULT GetMyObject([out,retval] IMyCOMObject** pTheObject);
};
//Library stuff
[
uuid(BEB8FFE9-4F15-42ED-8B6A-B755DB56442F),
helpstring("MyCOMObject Class"),
noncreatable
]
coclass MyCOMObject
{
[default] interface IMyCOMObject;
};
[
uuid(A9CE7233-D106-4C8A-9E29-29C34B99D56F),
helpstring("MyCOMControl Class")
]
coclass MyCOMControl
{
[default] interface IMyCOMControl;
};
//In MyCOMControl.h :
CComObject<CMyCOMObject>* m_pObj;
HRESULT FinalConstruct()
{
CComObject<CMyCOMObject>::CreateInstance(&m_pObj);
return S_OK;
}
STDMETHOD(GetMyObject)(IMyCOMObject** pObj);
//In MyCOMControl.cpp :
STDMETHODIMP CMyCOMControl::GetMyObject(IMyCOMObject** pObj)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
HRESULT hr;
hr = m_pObj->QueryInterface(&pObj);
if(FAILED(hr))
return hr;
return S_OK;
}
Thanks for any help folks
Martin

