Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call functions that receive floating point values using IDispatch.Invoke?

I'm having trouble calling a function that has a floating point argument and a floating point result, using IDispatch.Invoke.

Here's a minimal reproduction:

#include <atlbase.h>
#include <comutil.h>

int main(int argc, char* argv[])
{
    CoInitialize(NULL);
    CComPtr<IDispatch> wordapp;
    if (SUCCEEDED(wordapp.CoCreateInstance(L"Word.Application", NULL, CLSCTX_LOCAL_SERVER)))
    {
        CComVariant result;
        CComVariant centimeters((float)2.0);
        CComVariant retval = wordapp.Invoke1(L"CentimetersToPoints", &centimeters, &result);
    }
    return 0;
}

I'm using the ATL CComPtr to make things cleaner. But it's a very loose wrapper around IDispatch.Invoke.

When I run this, the call to Invoke1 fails and returns E_FAIL.

I suspect that the problem is related to the use of floating point arguments and/or return value. If I call a function that does not use such values, the invoke succeeds:

CComVariant retval = wordapp.Invoke0(L"ProductCode", &result);

I note that if I call the function from VBS, or from PowerShell, it succeeds. I'm presuming that they both use late bound IDispatch and so that would indicate that what I am attempting is at least possible.

So, how can I call this function using IDispatch?

like image 350
David Heffernan Avatar asked Jan 18 '26 05:01

David Heffernan


1 Answers

Well, that was a head-scratcher. The documentation for this "method" is very misleading, it is not a method. It behaves more like an indexed property and requires the DISPATCH_METHOD | DISPATCH_PROPERTYGET flags. CComPtr doesn't support that, you'll need to spin this by hand. This code worked:

    CComVariant result;
    CComVariant centimeters((float)2.0);
    DISPID dispid;
    LPOLESTR name = L"CentimetersToPoints";
    HRESULT hr = wordapp->GetIDsOfNames(IID_NULL, &name, 1, LOCALE_USER_DEFAULT, &dispid);
    assert(SUCCEEDED(hr));

    DISPPARAMS dispparams = { &centimeters, NULL, 1, 0};
    hr = wordapp->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT,
            DISPATCH_METHOD | DISPATCH_PROPERTYGET, &dispparams, &result, nullptr, nullptr);
    assert(SUCCEEDED(hr));
like image 125
Hans Passant Avatar answered Jan 19 '26 18:01

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!