在ATL中将接口作为参数传递

时间:2010-03-31 13:18:38

标签: dll atl

我有一个原生的C ++ DLL和两个类:

classA
{
void setNumber(int number);
int getNumber();
}
classB
{
void setclassA(classA*);
classA* getclassA();
}

我有一个包装本机C ++ DLL和两个接口的ATL dll:InterfaceForClassA,InterfaceForClassB。

InterfaceForClassA:

STDMETHODIMP CInterfaceForClassA::createClassAObject(void)
{
         ClassA* Aobject = new ClassA(); 
         return S_OK;
}
STDMETHODIMP CInterfaceForClassA::setNumberInClassA(SHORT pVal)
{     
     if(Aobject != NULL)
         Aobject->setNumber(pVal);
     return S_OK;
}
STDMETHODIMP CInterfaceForClassA::getNumberInClassA(SHORT* pVal)
{     
      if(Aobject != NULL)  
          *pVal = Aobject->getNumber();
      return S_OK;
}

InterfaceForClassB:

IInterfaceForClassA* clsAInterface;
STDMETHODIMP CInterfaceForClassB::setClassA(IInterfaceForClassA * val)
{
   val->QueryInterface(IID_IInterfaceForClassA,(void**)clsAInterface;
}
STDMETHODIMP CInterfaceForClassB::getClassA(IInterfaceForClassA ** returnVal)
{
   clsAInterface->QueryInterface(IID_IInterfaceForClassA,(void**)returnVal);
}

最后我有一个包含ATL dll的c#项目,在c#项目中我调用了ATL dll类:

        InterfaceForClassA clsa1 = new InterfaceForClassA();
        clsa1.createClassAObject();
        clsa1.setNumberInClassA(12);

        InterfaceForClassB clsb = new InterfaceForClassB();
        clsb.setClassA(clsa1);

        InterfaceForClassA clsa2 = new InterfaceForClassA();
        clsa2 = clsb.getClassA();

        Console.WriteLine("number: " + clsa2.getNumberInClassA());

当我运行c#项目时,它在上面的最后一行给出了NullReferenceException错误。你能救我吗?

1 个答案:

答案 0 :(得分:0)

您的CInterfaceForClassB :: setClassA实现不正确。它应该是(注意&):

STDMETHODIMP CInterfaceForClassB::setClassA(IInterfaceForClassA * val)
{
   val->QueryInterface(IID_IInterfaceForClassA,(void**)&clsAInterface);
}