Project/T-Set

JScript arrays and COM objects

SSKK 2011. 1. 15. 11:50
출처: 

MONDAY, AUGUST 13, 2007

JScript arrays and COM objects, part 1

In one of the projects I am doing I needed to create the COM object that is going to be used from JavaScript. It is a well-known scenario - the JScript implementations lets programmer instantiate any COM object that is an ActiveX automation-enabled, i.e. it implements an IDispatch interface. Then, you can call any method or manipulate any property of the COM object. It looks nice and perfect as long as you are using simple data types - numbers, string. Still, there is no problem even to pass the object. Your property may be even visible as an object to the script - you may pass back the pointer to the IDispatch implementation of some object as the property and it can be treated in script almost like a native JScript object.

However, it no longer looks so bright when you need to pass to/from your COM object an array. The problem is that what you call an array in JavaScript is the completely different thing than what you call an array in your programming language you use to create your COM object. To complicate things more, an array in JScript, an array in ActiveX world and an array in "serious" programming languages like C++ or Delphi are different objects. In C, C++ and pascal it is, simply, the segment of memory which contains consecutive elements of the same certain type. In ActiveX world and Visual Basic which is set in this world, array refers to what is called variant arrays, safe arrays or VBArrays, which are bound inside the VARIANT type and are still, more or less, block of memory. On the other hand, in JScript, the array is the object that has its own properties (in fact one - length) and methods. It is not hard to guess that it is in no way compatible with safe arrays.

Your COM object will use safe arrays as it is a standard way in ActiveX. Let us, firstly, concentrate on returning arrays from the function. We will consider the object Some.Object that exposes the following method:

[id(0x000002C0)]
HRESULT GetSomeArray([out, retval] VARIANT *retArr );
which may have the following implementation in Delphi:
function TSomeObject.GetSomeArray : OleVariant;
var
vals: array [0..2] of Variant;
begin
vals[0] := 'Hello';
vals[1] := 'World';
vals[2] := 'Dude';
Result := VarArrayOf(vals);
end;
In VBScript there would be no problem with dealing with the result of this function. In JScript, however, we get something which is not familiar - it is not an array as JScript understands it.
Is there any way to convert safe arrays to JScript arrays? Fortunately, the answer is affirmative. JScript architects has provided the class VBArray which is the JScript front-end to safe arrays. We can manage it in the following way:
var someObj = new ActiveXObject("Some.Object");
var arr = (new VBArray(someObj.GetSomeArray())).toArray();

alert(arr[0]);
We have used here toArray() method to convert the VBArray to the JScript array. We could also use getItem() method to directly access element of the array. Note, that script engines, both JScript and VBScript have the limitation - they can only process safe array containing elements of type Variant. Therefore, even if you want to pass an array of strings, make the array's element to be of type Variant.

OK, it was not so bad. But, what about passing an array to the function. Here, we encounter the real problem. We will solve it in the next post.

출처:

WEDNESDAY, AUGUST 15, 2007

JScript arrays and COM objects, part 2

In the previous post I have been discussing the scenario where we have COM object and the script in JScript and we need to interchange the array of data between them. I have demonstrated how to convert, in your JScript code, the vb-style array received from call to ActiveX object to the array native to JScript. To that, fortunately, the architects of JScript provided us with a tool - VBScript class. However, in reverse situation we don't have any object or routine in JScript scripting engine that would let us or help us converting JScript array to VBArray.

Eric Lippert in his blog states that, although he started writing code to manage conversion to VBArray, it was eventually abandoned and there is no way to do this.
And, actually, this is a truth. JScript engine does not provide us with any way to do that conversion. But why not try looking for it outside the engine but in what is by default available?
Fortunately, here our quest is successful and what we find is that there a COM object in WSH called Scripting.DictionaryIt is, well, as its name says, a dictionary, but what would be most important for you is that it has a method called Items which returns all the items in the dictionary as a VBArray object. So now, I am sure, you know what to do. Here is a code snippet of the function that converts JScript arrays into VBArray:

function GetVBArray(jsArray)
{
var dict =
new
ActiveXObject("Scripting.Dictionary");

for (i in jsArray)
{
dict.add(i, objJSArray[i]);
}

return dict.Items();
}

However, it may have some drawbacks like efficiency. But if it is not critical to your script it will suffice. On the other hand, if you are also an author of the COM object it would be better to just pass JScript array and deal with it in the code, wouldn't it?

If you read my previous post you probably remember that I wrote that in JScript arrays are nothing more than objects. You may also remember that JScript passes objects to automation objects as a pointer to IDispatch interface. Therefore, we may query the IDispatch object about the elements of array, can't we?

Below there is a piece of code in pascal (delphi) of the method that can both accept and process VBArrays and JScript arrays (to be precise, one-dimensional one):

procedure TSomeObject.ProcessArray(SomeArr: OleVariant);
var
i: integer;
ind: array [0..0] of integer;
begin
if VarIsArray(SomeArr) then // (1)
begin
for i := VarArrayLowBound(SomeArr, 1)
to
VarArrayHighBound(SomeArr, 1) do
begin
ind[0] := i;
ProcessElement(VarArrayGet(SomeArr, ind));
end;
end
else if VarIsType(SomeArr, VT_DISPATCH) then // (2)
begin
for i := 0 to SomeArr.length - 1 do
begin
ProcessElement(SomeArr.pop());
end;
end
else
raise EOleException.Create
('Parameter is not an array!',
E_INVALIDARG, '', '', 0);
end;

My example is in Delphi, but if you prefer, for instance, programming in C++ and ATL you can follow the same reasoning. However it will consume more code, since C++ semantics do not allow that you do late binding and you need to do that manually by pairs of calls to IDispatch's GetIDsOfNames and Invoke. In Delphi, we could use its magic of having IDispatch reference in Variant variable and leave it to Delphi to play with name resolving and calls to IDispatch methods.

Now let us analyze the above code. Firstly, in the if in (1) we are checking if the variant contains the traditional VBArray. If so, we process as we normally do with safe arrays. If not, we again examine our variant parameter if its content is IDispatch object. If so, it's probably the JScript array. Therefore, we can try getting the length property or get all elements by calls topop method. You may also get the value at the given index, but it cannot be done automatically in Delphi. All you need to do is to extract an IDispatch interface, invoke GetIDsOfNames for the given index (which as you know, need not be an integer) and then Invoke retrieved DISPID to get the actual value.

That is all about arrays in JScript and COM object, I wanted to say for now. I hope somebody will find it usable. Maybe, I will also post in the future sample in C++ and ATL, stay tuned ;).


출처:

TUESDAY, AUGUST 21, 2007

JScript arrays and COM objects, part 3

I have promised in my previous post that I will present also how to deal with JScript arrays in C++ code with ATL. Below, there is a code of a function, I have come up with, in C++ that gets the JScript array of integers and calculates the sum:

#include <string>
#include <sstream>
#define _C(oleop) hr = oleop; \
if (!SUCCEEDED(hr)) \
return hr;

STDMETHODIMP CHelloWorld::JSArrSum(VARIANT js_arr, LONG* Sum)
{
HRESULT hr;

/* checking if argument is an object */
if (!(js_arr.vt & VT_DISPATCH))
return E_INVALIDARG;

/* retrieving IDispatch */
IDispatch *disp = js_arr.pdispVal;
if (js_arr.vt & VT_BYREF)
disp = *(js_arr.ppdispVal);

/* getting array's length */
DISPPARAMS params;
FillMemory(¶ms, sizeof(DISPPARAMS), 0);
VARIANT res;

DISPID dl;
LPOLESTR ln = L"length";

_C(disp->GetIDsOfNames(IID_NULL, &ln, 1, LOCALE_USER_DEFAULT, &dl));

_C(disp->Invoke(dl, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
¶ms, &res, NULL, NULL));

VARIANT len1;
VariantInit(&len1);

_C(VariantChangeType(&len1, &res, 0, VT_I4));
LONG len = len1.lVal;

/* summing elements */

int total = 0;
for (int i = 0; i < len; i++)
{
std::stringstream ss;
ss << ind =" CComBSTR(ss.str().c_str());">GetIDsOfNames(IID_NULL, &ind, 1, LOCALE_USER_DEFAULT, &id));
_C(disp->Invoke(id, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, ¶ms, &res, NULL, NULL));

VARIANT val1;
VariantInit(&val1);

_C(VariantChangeType(&val1, &res, 0, VT_I4));
total += val1.lVal;
}

*Sum = total;

return S_OK;
}

What it does is simply the following:

  1. It is checked if an argument is some object (hopefully, a JScript array)
  2. IDispatch reference of an array is retrieved from the variant.
  3. The property length is obtained from the array's object as it is for any automation object. We receive some variant value, so we need to convert it to integer.
  4. For each element of an array its DISPID is queried and its value received, converted to integer, and summed up.
  5. It returns the sum of array's values.
It can be called from JScript as following:

var arr = new Array();
arr[0] = 10;
arr[1] = 15;
arr[2] = 2;

var obj = new ActiveXObject("ProgID.OfClass");
alert(obj.JSArrSum(arr));