Search code examples
comjscriptsafearray

How to access array elements of SAFEARRAY from MS JScript?


A COM object lives in a DLL. Its IDL looks roughly like this:

[
    object,
    uuid(51EB4046-221E-45EF-BD63-0D31B163647C),
    oleautomation,
    dual,
    pointer_default(unique)
]
interface IOne2OneNode : IDispatch
{
    // ...
    [propget, id(2), helpstring("property Vector")] HRESULT Vector([out, retval] VARIANT *pVal);
};

The DLL fills in *pVal with a SAFEARRAY of VT_R8 (using COleSafeArray).

I want to access the array elements from a JScript script that is executed with cscript.exe.

I tried node.Vector[1], but it reports

TestIDispatch.wsf(115, 2) runtime error in Microsoft JScript: 'node.Vector' is Null or not an object

(modulo German to English translation errors). Also, typeof node.Vector reports unknown.

After reading this answer, I tried

var vec = new VBArray(node.Vector).toArray();

but it reports runtime error in Microsoft JScript: VBArray expected.

How can I access the array elements from JScript?


Solution

  • JScript can only process SAFEARRAYs with element type VT_VARIANT. Any other element type is incompatible.

    It is correct to convert the returned array using

    var vec = new VBArray(node.Vector).toArray();
    

    but the COM server must create an array of VARIANTs, i.e., type code VT_VARIANT; VT_R8 will end up in a type mismatch error.

    Found in the responses to this post.