如何返回一个COM接口?

问题描述

我根据“构建本地COM服务器和客户端:分步示例”实现了客户端/服务器COM程序。 https://www.codeproject.com/Articles/8679/Building-a-LOCAL-COM-Server-and-Client-A-Step-by-S

我想编写一个名为“ ICreateMyCarReturnIStats”的函数以返回接口,但是失败。

ICreateMyCarReturnIStats返回了一个接口IStats,服务器的代码如下:

// define IStats interface
[object,uuid(FE78387F-D150-4089-832C-BBF02402C872),oleautomation,helpstring("Get the status @R_9_4045@ion about this car")]
interface IStats : IUnkNown
{
   HRESULT displayStats();
   HRESULT GetPetName([out,retval] BSTR* petName);
};

// define the ICreateMyCar interface
[object,uuid(5DD52389-B1A4-4fe7-B131-0F8EF73DD175),dual,helpstring("This lets you create a car object")]
interface ICreateMyCar : IUnkNown
{
   HRESULT SetPetName([in]BSTR petName);
   HRESULT SetMaxSpeed([in] int maxSp);
   HRESULT ICreateMyCarReturnIStats([out,retval] IStats** pIStats_ReturnVal);
   HRESULT GetReturnIStatus();
};

// library statement
[uuid(957BF83F-EE5A-42eb-8CE5-6267011F0EF9),version(1.0),helpstring("Car server with typeLib")]
library CarLocalServerLib
{
   importlib("stdole32.tlb");
   [uuid(1D66CBA8-CCE2-4439-8596-82B47AA44E43)]
   coclass MyCar
   {
      [default] interface ICreateMyCar;
      interface IStats;
      interface IEngine;
   };
};

文件

// ICreateMyCar
STDMETHODIMP_(IStats*) ICreateMyCarReturnIStats(IStats** pIStats_ReturnVal);
STDMETHODIMP GetReturnIStatus();

cpp

STDMETHODIMP_(IStats*) MyCar::ICreateMyCarReturnIStats(IStats** pIStats_ReturnVal)
{
    // declare variables
    HRESULT hr;
    IClassFactory* pICF = NULL;
    ICreateMyCar*  pICreateMyCar = NULL;
    IEngine*       pIEngine = NULL;
    IStats*        pIStats = NULL;


    hr = CoGetClassObject(CLSID_MyCar,CLSCTX_LOCAL_SERVER,NULL,IID_IClassFactory,(void**)&pICF);
    if (Failed(hr))
    {
        //ShowErrorMessage("CoGetClassObject()",hr);
        exit(1);
    }

    hr = pICF->CreateInstance(NULL,IID_ICreateMyCar,(void**)&pICreateMyCar);
    if (Failed(hr))
    {
        //ShowErrorMessage("CoGetClassObject()",hr);
        exit(1);
    }
    pICreateMyCar->QueryInterface(IID_IStats,(void**)&pIStats);

    *pIStats_ReturnVal = pIStats;

    return pIStats;
}
STDMETHODIMP MyCar::GetReturnIStatus()
{
    IStats*        pis = NULL;
    IStats*        pIStats = NULL;
    pis = this->ICreateMyCarReturnIStats(&pIStats);
    BSTR carName1 = SysAllocString(OLESTR("COMCar?!"));
    BSTR carName2 = SysAllocString(OLESTR("COMCar?!"));
    pIStats->GetPetName(&carName1);//success
    pis->GetPetName(&carName2);//success

    return S_OK;
}

客户代码如下:

pICreateMyCar->GetReturnIStatus();
IStats*        pIStats = NULL;
IStats*        pIStats_alley = NULL;
pIStats_alley = pICreateMyCar->ICreateMyCarReturnIStats(&pIStats);
pIStats->GetPetName(&carName);//success
pIStats_alley->GetPetName(&carName);//fail

// I'd like to use the paremeter pIStats_alley,not pIStats.

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)