return array from com object

2019-02-16 03:28发布

问题:

I want to pass a list of alarm names from COM to VBScript used in ASP pages. If the method name is GetAlarms, What would be the signature of the method?. The number of alarms returned by GetAlarms will vary.

Does VBScrip support Safe Array?

回答1:

The declaration in the *.idl file would look like this:

[id(1)] HRESULT GetAlarms([out,retval] SAFEARRAY(VARIANT)* pAlarms);

The corresponding C++ method would look like this:

STDMETHODIMP CMyClass::GetAlarms(SAFEARRAY** pAlarms)
{
    CComSafeArray<VARIANT> alarms(3);
    CComVariant value;

    value = L"First Alarm";
    alarms.SetAt(0, value);

    value = L"Second Alarm";
    alarms.SetAt(1, value);

    value = L"Third Alarm";
    alarms.SetAt(2, value);

    *pAlarms = alarms.Detach();

    return S_OK;
}

And finally, here is a sample VBScript that uses the above method:

Set obj = CreateObject("MyLib.MyClass")
a = obj.GetAlarms
For i = 0 To UBound(a)
   MsgBox a(i)
Next

In ASP, of course, you would use something else instead of MsgBox.



标签: c++ com vbscript