我正在使用IConnectionPoint和IConnectionPointContainer概念在cpp中实现c#事件,就像从托管代码到非托管代码一样,但我得到IConnectionPoint对象为null,没有与接口建立连接。
这是我的c#代码:
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("3E903445-F6A8-416F-AD4A-1FFBE571620A")]
public interface ICalculator
{
int Add(int Num1, int Num2);
void SetHandle(IntPtr handle);
}
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("9CD6E042-EB56-4D9A-80EE-6556F8BC2C2D")]
public interface ICalculatorEvents
{
void Completed(int Result);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("41761326-67E8-4D0D-9170-2E4C3885A3C3")]
public class Calculator : ICalculator
{
public delegate void AddNumbers(int first,int second);
public event AddNumbers OnClick;
private IntPtr _windowHandle;
public int Add(int Num1, int Num2)
{
int Result = Num1 + Num2;
return Result;
}
public void SetHandle(IntPtr handle)
{
_windowHandle = handle;
}
public void Fire(int a,int b)
{
if (OnClick != null)
OnClick(a,b);
}
}
这是我的cpp代码:
IConnectionPointContainer * pCPC;
IConnectionPoint * pCP; //these are declared as a member
DWORD dwAdvise; //variable,shown here for completeness
//check if this interface supports connectable objects
hr= _calculator->QueryInterface(IID_IConnectionPointContainer, (void**)&pCPC);//_calculator is the object of the c# calculator class.
if ( !SUCCEEDED(hr) )
{
return hr;
}
//
//ok it does now get the correct connection point interface
// in our case IID_IAddEvents
const IID &iid=StringMethodInCSharp::IID_ICalculatorEvents;//ICalculatorEvents is interface in c#
// pCP->GetConnectionInterface();
pCPC->FindConnectionPoint(iid,&pCP);
_calculator->QueryInterface(iid, (void**)&pCP);//here i am getting null value of pCP,which i don't want.
IUnknown *pSinkUnk;
if ( !SUCCEEDED(hr) )
{
return hr;
}
//we have done with the connection point container interface
long * pRetVal =new long();
pCPC->Release();
//pCP=pCPC;
CSink *pSink=new CSink();//CSink is the class in cpp where i have implemented ICalculatorEvents Interface.
if ( NULL == pSink )
{
return E_FAIL;
}
hr = pSink->QueryInterface (IID_IUnknown,(void **)&pSinkUnk);
hr = pCP->Advise(pSinkUnk,&dwAdvise);//here i am getting null ptr exception because pCP is getting null.