问题描述
我无法使用 IDispatch.Invoke
调用具有浮点参数和浮点结果的函数。
I'm having trouble calling a function that has a floating point argument and a floating point result, using IDispatch.Invoke
.
这是最小的复制品:
#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", ¢imeters, &result);
}
return 0;
}
我使用ATL CComPtr
使事情更清洁。但是它是 IDispatch.Invoke
的一个非常松散的包装。
I'm using the ATL CComPtr
to make things cleaner. But it's a very loose wrapper around IDispatch.Invoke
.
当我运行这个,调用 Invoke1
失败并返回 E_FAIL
。
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);
我注意到如果我从VBS或PowerShell调用函数,它会成功。我假设他们都使用晚绑定 IDispatch
,这样就表明我试图至少是可能的。
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.
那么,如何使用 IDispatch
调用此函数?
So, how can I call this function using IDispatch
?
推荐答案
好吧,这是一个头脑。这个方法的文档是非常误导,它不是一种方法。它的行为更像一个索引属性,需要DISPATCH_METHOD | DISPATCH_PROPERTYGET标记。 CComPtr不支持,你需要手动旋转。此代码工作:
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 = { ¢imeters, NULL, 1, 0};
hr = wordapp->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_METHOD | DISPATCH_PROPERTYGET, &dispparams, &result, nullptr, nullptr);
assert(SUCCEEDED(hr));
这篇关于如何使用IDispatch.Invoke调用接收浮点值的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!