Search code examples
c++comsmart-pointers

Trying to call a function via a pointer to a smart pointer to a COM interface


I followed the Microsoft tutorial here (with a little help from SO) to call a COM object from C++ code.

Step 9 of the tutorial says:

To call the managed DLL, add the following code to the _tmain function:

// Initialize COM.
HRESULT hr = CoInitialize(NULL);

// Create the interface pointer.
ICalculatorPtr pICalc(__uuidof(ManagedClass));

When I used these lines of code in my file, they worked fine, and I called functions on the COM interface successfully.

Now, I need to access pICalc in 2 static functions, so I thought of making it a static class variable (I am aware that static has 2 different meanings in this sentence).

This is my code:

In MyCPlusPlusClass.h:

static ICalculatorPtr* pICalc;

In MyCPlusPlusClass.cpp:

//Pointer definition
ICalculatorPtr* MyCPlusPlusClass::pICalc;

and in a static function:

pICalc = new ICalculatorPtr(__uuidof(ManagedClass));

but when I tried to call a function with

(*pICalc)->SomeICalcFunction();

I got

_com_issue_error(Int32) at _com_ptr_t ...

I'm mostly a C# programmer, so am I just making a stupid syntax mistake in C++?

EDIT: In the .tlh file, there is

struct __declspec(uuid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")) _ManagedClass

_COM_SMARTPTR_TYPEDEF(ICalc, __uuidof(ICalc));
_COM_SMARTPTR_TYPEDEF(_ManagedClass, __uuidof(_ManagedClass));

virtual HRESULT __stdcall SomeICalcFunction (BSTR * pRetVal) = 0;

Solution

  • Ok, I think, that you must do the following.

    In MyCPlusPlusClass.h:

    change

    static ICalcPtr* pICalc;
    

    to

    static ICalcPtr pICalc;
    

    In MyCPlusPlusClass.cpp:

    change

    //Pointer definition
    ICalcPtr* MyCPlusPlusClass::pICalc;
    

    to

    ICalcPtr MyCPlusPlusClass::pICalc;
    

    In all of your static functions:

    if(pICalc == NULL)
    {
        if(FAILED(pICalc.CreateInstance(__uuidof(ManagedClass))))
            std::cout << "Can't create pICalc" << std::endl;
    }
    

    And then use:

    pICalc->SomeICalcFunction();
    

    I really dont understand why you need static functions. Make all them non-static and pICalc non-static too. That will be more cleaner.