c++comidispatch

IDispatch Invoke() returns Type mismatch


I'm unable to successfully invoke create_session member. It's return Type mismatch

// COM class -> member
virtual HRESULT __stdcall create_session(
        /*[in]*/ BSTR pbszName,
        /*[in]*/ long i32Value ) = 0;

Trying to invoke create_session method as follow:

// test.cpp
HRESULT create_session( IDispatch *dispatch, WCHAR *member ) {
    // WCHAR *member = tlib_help::s2ws( "create_session" );
    DISPID dispid = -1;
    HRESULT hr = dispatch->GetIDsOfNames( IID_NULL, &member, 1, LOCALE_SYSTEM_DEFAULT, &dispid );
    if ( SUCCEEDED( hr ) ) {
        DISPPARAMS *dispparams = new DISPPARAMS( );
        dispparams->cArgs = 2;
        dispparams->cNamedArgs = 1;
        VARIANTARG *rgvarg = new VARIANTARG[dispparams->cArgs];
        rgvarg[0].vt = VARENUM::VT_BSTR;
        rgvarg[0].bstrVal = _bstr_t( "loing_info" );
        rgvarg[1].vt = VARENUM::VT_UI4;
        rgvarg[1].lVal = 12;//i32Value;
        dispparams->rgvarg = rgvarg;
        dispparams->rgdispidNamedArgs = &dispid;
        EXCEPINFO pExcepInfo; UINT puArgErr;
        HRESULT hr;
        VARIANT pVarResult;
        hr = dispatch->Invoke(
            dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD,
            dispparams, &pVarResult, &pExcepInfo, &puArgErr
        );
        delete dispparams;
        delete[] rgvarg;
    }
    return hr;
}

I'm unable to figure it out, what is the reason of this error.


Solution

  • The IDispatch::Invoke() method must be called with parameters in reverse order, as stated in the official documentation:

    Implementing IDispatch / Passing Parameters:

    The arguments are passed in the array rgvarg[ ], with the number of arguments passed in cArgs. The arguments in the array should be placed from last to first, so rgvarg[0] has the last argument and rgvarg[cArgs -1] has the first argument.

    Also, in your case, you don't need "named arguments", only "positional arguments". If cNamedArgs is 0, all of the elements of rgvarg[ ] represent positional arguments.