【问题标题】:Invalid argument when passing ByteArray to javascript through Rhino通过 Rhino 将 ByteArray 传递给 javascript 时参数无效
【发布时间】:2020-02-26 11:20:53
【问题描述】:

我正在使用 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);
}

科特林

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】:

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 已实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多