How to Properly Return an Array of Strings from an ActiveX Object to JScript

If you are working with a Win32 API and need to return an array of strings from an ActiveX object to JScript, you may run into some challenges. This problem typically arises when the strings appear to get ’lost’ during the transfer. Understanding the relationship between COM objects, ActiveX, and JScript is crucial for successful data handling in these environments. In this blog post, we will walk through the correct approach to achieve this.

The Problem

You have defined an interface in your IDL (Interface Definition Language) file for a COM object which includes a method that returns an array of strings. Specifically, the function signature appears as follows:

HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);

While the function itself operates correctly, the issue arises when the strings are assigned to a variable in JavaScript, resulting in the strings seemingly being lost. We need to ensure the data is transferred correctly.

The Solution

To properly pass the array of strings from your ActiveX object to JScript, follow these detailed steps:

Step 1: Wrap the SAFEARRAY in a VARIANT

To facilitate the communication between the COM object and JScript, you need to wrap the SAFEARRAY in a VARIANT before passing it back. This allows for proper handling of the array and ensures no data loss occurs. Below is the modified function code to achieve this:

HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)
{
   // Declare a variant to hold the array.
   _variant_t ret;
   // Set the variant type to an array of variants.
   ret.vt = VT_ARRAY | VT_VARIANT;
   ret.parray = rgBstrStringArray; // Assign the SAFEARRAY.
   *pvarBstrStringArray = ret.Detach(); // Detach it for returning.
   return S_OK; // Return success.
}

Step 2: Use VBArray in JScript

Once the data is wrapped in a VARIANT and successfully returned from ActiveX, you can utilize the VBArray object in your JScript code to unpack the data properly. The line of code you’ll need is:

var jsFriendlyStrings = new VBArray(axOb.GetArrayOfStrings()).toArray();

This single line effectively converts the returned VARIANT into a JavaScript-friendly array of strings, allowing you to handle the data as needed.

Conclusion

Handling the transfer of an array of strings from an ActiveX object to JScript comes down to understanding how to manipulate COM objects and JavaScript interactions. By wrapping your SAFEARRAY in a VARIANT and using the VBArray to unpack it, you can ensure that all data is correctly passed without loss.

Now, you should be equipped with the right approach to successfully return and utilize arrays of strings in your administrative scripts. Happy coding!