Returning a JS Array to JavaScript from a C++/JavaScript XPCOM object access through XPConnect

Cited from

http://groups.google.co.in/group/mozilla.dev.tech.xpcom/browse_thread/thread/

37b18383a15b82a7/b26a4e4568c3caf4?lnk=gst&q=nsiarray&rnum=2&hl=en#b26a4e4568c3caf4

// XPIDL

void getArray(out unsigned long count, [array, size_is(count), retval] out long retv);

// C++  XPCOM

NS_IMETHODIMP MyComponent::GetArray(PRUint32* count, PRInt32** retv) {

    *count = 10;

    *retv = (PRInt32*)nsMemory::Alloc(*count * sizeof(PRInt32));

    for (int i = 0; i < 10; ++i) (*retv)[i] = i;

    return NS_OK;

}

// JavaScript  XPCOM

Component.prototype.getArray = function(count, retv) {

    count.value = 10; // You must assign the length of array to count.

    var array = new Array();

    ……..

    return array;

}

// JavaScript Calling

var arr = myComponent.getArray({});

Blogged with Flock