quickjs-emscripten icon indicating copy to clipboard operation
quickjs-emscripten copied to clipboard

Having troubles with ArrayBuffer

Open Tadeuchi opened this issue 1 year ago • 1 comments

Hi,

I'm having troubles with passing array buffer. I followed the first example in the readme, but with additional code to handle array buffer. And then tried doing some modifications, but... every time the results are mostly undefined... That leads me to conclusion that I must be doing something wrong (very likely) or there may be an implementation issue?

Following code

import { getQuickJS } from "quickjs-emscripten"

async function main() {
    const QuickJS = await getQuickJS()
    const vm = QuickJS.newContext()

    const world = vm.newString("ArrayBuffer")
    const ab = new Uint8Array([1, 1])
    console.log(ab[0], ab.length)
    const ones = vm.newArrayBuffer(ab);
    vm.setProp(vm.global, "NAME", world)
    vm.setProp(vm.global, 'ones', ones)
    world.dispose()
    ones.dispose()

    const result = vm.evalCode(`"Hello " + NAME + ", why are you " + ones.length + "?"`)
    if (result.error) {
        console.log("Execution failed:", vm.dump(result.error))
        result.error.dispose()
    } else {
        console.log("Success:", vm.dump(result.value))
        result.value.dispose()
    }

    vm.dispose()
}

main().then(r => console.log('Finished'));

produces following result

1 2
Success: Hello ArrayBuffer, why are you undefined?
Finished

Tadeuchi avatar Mar 26 '24 09:03 Tadeuchi

Hi, I'm also seeing the same thing. When I log the length of the arraybuffer created using vm.newArrayBuffer, it shows as undefined in the output of vm.evalCode.

It can be easily recreated in the browser like so:

<!doctype html>
<script type="module">
  import { getQuickJS } from "https://esm.sh/[email protected]"
  const QuickJS = await getQuickJS()

  const vm = QuickJS.newContext()

  const string = '12'
  const arrayBuffer = new Uint8Array([1, 2]).buffer

  console.log('string.length', string.length)
  console.log('arrayBuffer.length', arrayBuffer.byteLength)

  const vmString = vm.newString(string)
  const vmArrayBuffer = vm.newArrayBuffer(arrayBuffer)

  vm.setProp(vm.global, 'vmString', vmString)
  vm.setProp(vm.global, 'vmArrayBuffer', vmArrayBuffer)

  console.log('vmString.length', vm.dump(vm.evalCode('vmString.length').value))
  console.log('vmArrayBuffer.length', vm.dump(vm.evalCode('vmArrayBuffer.length').value))

  vmString.dispose()
  vmArrayBuffer.dispose()
  vm.dispose()
</script>

Output:

string.length 2
arrayBuffer.length 2
vmString.length 2
vmArrayBuffer.length undefined

flawiddsouza avatar Apr 20 '24 22:04 flawiddsouza