Fast binary data exchange between JavaScript and C/C++ with SpiderMonkey JS engine

StackOverflow https://stackoverflow.com/questions/15517473

  •  24-03-2022
  •  | 
  •  

문제

Recently I learned that there are "External Arrays" in V8. So when you embed V8 in your app, you can map your C-array to JS-array, and even choose a type, either it's char, word, int etc. This can significantly speed up data exchange between JS and C. Now the question is there something like that in SpiderMonkey?

I tried google for "spidermonkey external arrays", "binary arrays", "map arrays" and some more, no luck so far.

I have SpiderMonkey source code, but it will take ages to familiarize with it.

도움이 되었습니까?

해결책

In SpiderMonkey you can use ArrayBuffer.

var buffer = new ArrayBuffer(16)
var int32View = new Int32Array(buffer);
for (var i = 0; i < int32View.length; i++) {
  int32View[i] = i * 3
}
array_dump(buffer)

now C++ part:

#include "js/jstypedarray.h"

static JSBool my_array_dump(JSContext *cx, uintN argc, jsval *vp) {
    JSObject *obj;
    JS_ValueToObject(cx, vp[0 + 2], &obj);
    js::ArrayBuffer *A;
    A = js::ArrayBuffer::fromJSObject(obj);
    int *B = (int*) A->data;
    for (int i = 0; i < A->byteLength / 4; i++) printf("%i ", B[i]);
    return JS_TRUE;
}

Seems like this way you can pass huge amounts of data between JS and C/C++ with virtualy no overhead.

Of course it would be better to have this clearly explained in SpiderMonkey docs. But as it often happens when you hack into Mozilla projects, you eventually end up digging the includes and sources, so I think this answer might be useful for somebody.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top