Creating Javascript Arrays and other objects from C++ - xfgr.com Click here to Skip to main content
 

Creating Javascript Arrays and other objects from C++

How to create Javascript Arrays and other objects from C++ code and pass them to the script.

Introduction

Javascript has some built-in classes like Object, Array or Date. It is often asked how to create instances of these classes from C++. Assuming you are familiar with COM you should be able to understand this solution:

How does it work?

To create new instances you would usually write Javascript code like:

var o = new Array();

If you host JScript in a C++ application (by using the scripting host directly or by using the WebBrowser-control to display a website with Javascript code embedded) you can't simply call new from your C++ code. Also there is no way to create an array via CoCreateInstance since you don't have a CLSID. Instead you have to do manually what JScript does when you construct a new object.

The following happens when you use the new-operator in JScript:

  1. The object on which new is called will be asked for a property with the name of the class of which you want a new instance (e.g. "Array").
  2. The returned property is asked for an IDispatchEx interface.
  3. InvokeEx is called on the returned interface with a DISPID of 0 and the flag DISPATCH_CONSTRUCT. This will construct the instance and return the newly created object.

After these steps you will have your Array.

Obtain the scripting object

There are usually two situations, where you have to deal with Javascript from your C++ application. One is, that you host a WebBrowser-control to display HTML pages, the second is that you use the JScript scripting host directly. In the second case you will have some IActiveScript pointer somewhere. Just call GetScriptDispatch() on that interface to get the scripting object:

// pScriptEngine is of type IActiveScript
// SCRIPT_ITEMNAME is the name you specified in IActiveScript::AddNamedItem
//     can be NULL to retreive the the object containing all global members
CComPtr<IDispatch> pScriptDisp;
HRESULT hr = pScriptEngine->GetScriptDispatch(SCRIPT_ITEMNAME, &pScriptDisp);
if (FAILED(hr))
  return hr;
// pScriptDisp is now the scripting object

If you host a WebBrowser-control you will have a IWebBrowser2 pointer. Ask for the current IHTMLDocument2, ask this document for the parent window (IHTMLWindow2 interface). This will be the scripting object:

// spBrowser is of type IHTMLWindow2
CComPtr<IDispatch> spDoc;
hr = spBrowser->get_Document(&spDoc);
if (FAILED(hr))
  return hr;

CComQIPtr<IHTMLDocument2> spHTMLDoc(spDoc);
if (!spHTMLDoc)
  return E_NOINTERFACE;

CComPtr<IHTMLWindow2> spWindow;
hr = spHTMLDoc->get_parentWindow(&spWindow);
if (FAILED(hr))
  return hr;

CComQIPtr<IDispatch> pScriptDisp(spWindow);
if (!pScriptDisp)
  return E_NOINTERFACE;
// pScriptDisp should now be scripting object

Obtaining the object constructor

Using the new operator in Javascript first asks for a property contained in the object on which new is called. So if you say new Array() inside the Javascript of an HTML page, the window object is the one you ask for a property with the name "Array". Everything inside Javascript is in fact a property of something. If you write the following Javascript code inside a HTML page

function doSomething()
{
  // ...
}

you add a property of type function to your window object with the name of "doSomething".

If you then construct a new instance by saying var o = new doSomething(); you call this property in a "special way" which is different then just saying var o = doSomething();. The latter will obtain the DISPID for doSomething and call Invoke on the window-object with this DISPID and the flag DISPATCH_METHOD. Using var o = new doSomething(); queries for a property named "doSomething" (which is also an object) and then call InvokeEx on this object with the flag DISPATCH_CONSTRUCT. But first let's get the property named "Array":

// get DISPID for "Array"
DISPID did = 0;
LPOLESTR lpNames = {L"Array"};
hr = pScriptDisp->GetIDsOfNames(IID_NULL, lpNames, 1, LOCALE_USER_DEFAULT, &did);
if (FAILED(hr))
  return hr;

// invoke pScriptDisp with DISPATCH_PROPERTYGET for "Array"
CComVariant vtRet;
DISPPARAMS params = {0};
CComVariant vtResult;
hr = pScriptDisp->Invoke(did, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, ¶ms
  , &vtResult, NULL, NULL);
if (FAILED(hr))
  return hr;
// vtResult should be of type VT_DISPATCH and contain the creator for Array

Now we have something like a creator for Array objects. The creator we will query now for a new Array. This is done by first getting an IDispatchEx interface from the creator:

// get IDispatchEx on returned IDispatch
CComQIPtr<IDispatchEx> creator(vtResult.pdispVal);
if (!creator)
  return E_NOINTERFACE;

The IDispatchEx interface extends IDispatch and supports objects that can be dynamically expanded with new properties. This is exactly the way our new propery doSomething is added to the window, by using its IDispatchEx interface. (see for details about IDispatchEx). Here we only need the InvokeEx method which is:

HRESULT InvokeEx(
   DISPID id,
   LCID lcid,
   WORD wFlags,
   DISPARAMS *pdp,
   VARIANT *pVarRes, 
   EXCEPINFO *pei, 
   IServiceProvider *pspCaller 
);

Using id = DISPID_VALUE and wFlags = DISPATCH_CONSTRUCT does the constructor magic:

// creator is of type IDispatchEx
DISPPARAMS params = {0};
CComVariant vtResult;
HRESULT hr = creator->InvokeEx(DISPID_VALUE, LOCALE_USER_DEFAULT, DISPATCH_CONSTRUCT
  , ¶ms, &vtResult, NULL, NULL);
// vtResult should contain the newly created object

If everything went well you have the newly created object now, weather it is a built-in-object or some object you defined in Javascript. Yes, of course you can also construct objects you defined in your js-code

function MyObject()
{
  this.foo = "bar";
}

by asking for a property named "MyObject". And that's more ore less all.

Oh, yes, you might want to pass some parameters to your constructor. Use the DISPPARAMS parameter in the InvokeEx call to pass arguments. Remember that the parameters have to be given in right-to-left-order, so the first parameter that arrives at the constructor is the last one in DISPPARAMS::rgvarg.

Adding values

If you created a new Object or Array you may want to add values to the new object. This is also done via the IDispatchEx interface using GetDispID and InvokeEx. First we need the DISPID for the name (or index in case of an Array) of the property to be added. IDispatchEx offers the method GetDispID for this:

HRESULT GetDispID(
   BSTR bstrName,
   DWORD grfdex,
   DISPID *pid
);

This property doesn't exist yet. To create it pass the flag fdexNameEnsure in grfdex, that will ensure that a property with the name bstrName will be created if it does not exist already. Initially this new property will be a VARIANT of type VT_EMPTY. After you have the new DISPID all you have to do is call InvokeEx with DISPATCH_PROPERTYPUT to add the value:

// theObject is of type IDispatchEx and is the js-Array
DISPID did = 0;
hr = theObject->GetDispID(CComBSTR(L"0"), fdexNameEnsure, &did);
if (FAILED(hr))
  return hr;
CComVariant data(_T("bar"));
DISPID namedArgs = {DISPID_PROPERTYPUT};
DISPPARAMS params = {&data, namedArgs, 1, 1};
hr = theObject->InvokeEx(did, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, ¶ms,
  NULL, NULL, NULL);

As you can see the rgdispidNamedArgs member of DISPPARAMS is used here, otherwise the call will fail with DISP_E_PARAMNOTOPTIONAL.

Putting it all together our PutJsArray looks like the following now. I use a CAtlArray<CComVariant> which is typedef'ed to CAtlVariantArray to pass the values and a js-function named lpsName that is been called to pass the newly created array to Javascript.

HRESULT CJsArrayView::PutJsArray(LPOLESTR lpsName, CAtlVariantArray& data)
{
  // get script dispatch
  CComPtr<IDispatch> scriptDispatch;
  HRESULT hr = GetScriptDispatch(&scriptDispatch);
  if (FAILED(hr))
    return hr;
  ATLASSERT(scriptDispatch);

  // get DISPID for "Array"
  DISPID did = 0;
  LPOLESTR lpNames = {L"Array"};
  hr = scriptDispatch->GetIDsOfNames(IID_NULL, lpNames, 1, LOCALE_USER_DEFAULT, &did);
  if (FAILED(hr))
    return hr;

  // invoke scriptdispatch with DISPATCH_PROPERTYGET for "Array"
  CComVariant vtRet;
  DISPPARAMS params = {0};
  CComVariant vtResult;
  hr = scriptDispatch->Invoke(did, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, ¶ms, &vtResult, NULL, NULL);
  if (FAILED(hr))
    return hr;
  // check result: should be a VT_DISPATCH
  if ((VT_DISPATCH != vtResult.vt)  (NULL == vtResult.pdispVal))
    return DISP_E_TYPEMISMATCH;

  // get IDispatchEx on returned IDispatch
  CComQIPtr<IDispatchEx> prototype(vtResult.pdispVal);
  if (!prototype)
    return E_NOINTERFACE;

  // call InvokeEx with DISPID_VALUE and DISPATCH_CONSTRUCT to construct new array
  vtResult.Clear();
  hr = prototype->InvokeEx(DISPID_VALUE, LOCALE_USER_DEFAULT, DISPATCH_CONSTRUCT, ¶ms, &vtResult, NULL, NULL);
  if (FAILED(hr))
    return hr;

  // vtresult should contain the new array now.
  if ((VT_DISPATCH != vtResult.vt)  (NULL == vtResult.pdispVal))
    return DISP_E_TYPEMISMATCH;

  // get IDispatchEx on returned IDispatch
  CComQIPtr<IDispatchEx> theObject(vtResult.pdispVal);
  if (!theObject)
    return E_NOINTERFACE;

  // add values by invoking InvokeEx
  CString sName;
  for(size_t n = 0; n < data.GetCount(); n++)
  {
    sName.Format(_T("%i"), n);
    hr = theObject->GetDispID(CComBSTR(sName), fdexNameEnsure, &did);
    if (FAILED(hr))
      break;
    DISPID namedArgs = {DISPID_PROPERTYPUT};
    DISPPARAMS p = {&data[n], namedArgs, 1, 1};
    hr = theObject->InvokeEx(did, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &p, NULL, NULL, NULL);
    if (FAILED(hr))
      break;
  }

  // now call the js-function in lpsName with the array as parameter
  params.cArgs = 1;
  params.rgvarg = &vtResult;

  hr = CallJs(scriptDispatch, lpsName, ¶ms);

  return hr;
}

The sample code

The ZIP contains a sample project based on WTL and ATL. All the important code is contained in the view class CJsArrayView. It can easily be changed to MFC or for usage with neither MFC or ATL or adapted to create other objects than Array or Object.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

 
imagiro


Software Developer

Germany Germany

Member
Born in 1968 I do programming since over 25 years now. I started with Basic on a ZX81 and with hacking hexcodes in a Microprofessor before I switched to C++ and other languages.

Since more than 10 years I work as a professional software developer, currently as a freelancer.

Sign Up to vote for this article
Add a reason or comment to your vote: x
 

Comments and Discussions

Hint: For improved responsiveness use Internet Explorer 4, Firefox or above. Ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
FAQ FAQ   
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralDefinitely looks like looking intomemberJohnWallis424:49 21 Jun '10  
GeneralRe: Definitely looks like looking intomemberimagiro4:56 21 Jun '10  
GeneralRe: Definitely looks like looking intomemberJohnWallis425:01 21 Jun '10  
GeneralRe: Definitely looks like looking intomemberJohnWallis425:07 21 Jun '10  
GeneralRe: Definitely looks like looking intomemberimagiro5:09 21 Jun '10  
GeneralRe: Definitely looks like looking intomemberJohnWallis425:17 21 Jun '10  
GeneralRe: Definitely looks like looking intomemberJohnWallis425:24 21 Jun '10  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink Privacy Terms of Use
Last Updated: 26 Jun 2010

2010 by imagiro
Everything else