using Java Arrays in Rhino

1,596 views
Skip to first unread message

Chris

unread,
Jun 7, 2012, 6:16:18 PM6/7/12
to mozilla-rhino
Consider the following code:

int[] x = { 1, 2, 3, 4 };
scope.put("arr", scope, Context.toObject(x,
scope));
cx.evaluateString(scope, "arr.push(5, 6);", "test", 1, null);

This throws an array index out of bounds exception. I assume because
the array is backed by Java. However, why doesn't Rhino take care of
expanding the array for me? It would be very useful to pass Java
arrays to javascript functions that use push and not get an
exception. Is there a way to accomplish this?

gabriel munteanu

unread,
Jun 11, 2012, 6:40:04 AM6/11/12
to mozill...@googlegroups.com
I guess what you are looking for is the wrapper mechanism which exists
for primitives.
check out this thread:
https://groups.google.com/forum/?fromgroups#!topic/mozilla-rhino/bGvfnSkIxG8
I think you have to implement your own WrapFactory, and handle the array case.
and then , call this:
ContextFactory.initGlobal(myContextFactory);
I think this was done in ringo [http://ringojs.org], but i don't seem
to find it now, all i could see were these:
https://github.com/ringo/ringojs/tree/master/src/org/ringojs/wrappers

cheers, jgabios

swet Hihoria

unread,
Jun 27, 2012, 5:49:55 AM6/27/12
to mozill...@googlegroups.com
Use Context.newArray() method to create a new array for javascript then put into your scope.

And Array.push() accept javascript array. correcting arr.push([5,6])
Reply all
Reply to author
Forward
0 new messages