首页 > 解决方案 > 如何返回 COM 接口?

问题描述

我根据“Building a LOCAL COM Server and Client: A Step by Step Example”实现了一个客户端/服务器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 information 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),
 oleautomation, 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.

在此处输入图像描述

标签: c++comidl

解决方案


推荐阅读