[通过Rhino将ByteArray传递给javascript时无效的参数

问题描述 投票:0回答:1

我正在使用Rhino评估一些javascript,在这里我只是将ByteArray从kotlin传递给Javascript中的函数。我知道这样说不好,但是我在Swift和.Net Core中使用了相同的Js文件,而在这种情况下,该行没有问题。

如下所示,我将bytes,一个ByteArray,传递给JS函数decodeByteArray()。失败的那一行是我用注释//invalid argument

标记的那一行

我已经检查了ByteArray的内容,并且符合预期。

我是在做错什么还是在其中遗漏了什么?

Javascript

function decodeByteArray(buf) {
    var pbf = new Pbf(buf);
    return JSON.stringify(decode(pbf));
}

function Pbf(buf) {
    this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf); 
    this.pos = 0;
    this.type = 0;
    this.length = this.buf.length;
    setUp(this);
}

Kotlin

private fun decodePbfBytes(bytes: ByteArray?): Any? {
    var jsResult: Any? = null;

    var params = arrayOf(bytes)

    val rhino = org.mozilla.javascript.Context.enter()
    rhino.optimizationLevel = -1
    rhino.languageVersion = org.mozilla.javascript.Context.VERSION_ES6
    try{
        val scope = rhino.initStandardObjects()
        val assetManager = MyApp.sharedInstance.assets
        val input = assetManager.open("pbfIndex.js") //the js file containing js code
        val targetReader = InputStreamReader(input)
        rhino.evaluateReader(scope, targetReader, "JavaScript", 1,null)
        val obj = scope.get("decodeByteArray", scope)
        if (obj is org.mozilla.javascript.Function){
            jsResult = obj.call(rhino, scope, scope, params)
            jsResult = org.mozilla.javascript.Context.toString(jsResult)
        }
    }catch (ex: Exception){
        Log.e("Error", ex.localizedMessage)
    }finally {
        org.mozilla.javascript.Context.exit()
    }

    return jsResult
}
arrays kotlin rhino
1个回答
0
投票

Rhino的TypedArray支持有点缺乏(请参阅https://mozilla.github.io/rhino/compat/engines.html#ES2015-built-ins-typed-arrays

我无法让构造函数直接获取一个字节[],但在转换为javascript数组后就可以使用。

我相信将new Uint8Array(buf);更改为new Uint8Array(Array.from(buf));

虽然未实现Uint8Array.from,但未实现Array.from。>

© www.soinside.com 2019 - 2024. All rights reserved.