node.js - How to cast an `ArrayBuffer` to a `SharedArrayBuffer` in Javascript? - Stack Overflow

Take the following snippet:const arr = [1.1, 2.2, 3.3]const arrBuffer = (Float32Array.from(arr)).buffe

Take the following snippet:

const arr = [1.1, 2.2, 3.3]
const arrBuffer = (Float32Array.from(arr)).buffer

How would one cast this ArrayBuffer to a SharedArrayBuffer?

const sharedArrBuffer = ...?

Take the following snippet:

const arr = [1.1, 2.2, 3.3]
const arrBuffer = (Float32Array.from(arr)).buffer

How would one cast this ArrayBuffer to a SharedArrayBuffer?

const sharedArrBuffer = ...?
Share Improve this question asked Jan 9, 2019 at 14:29 TomTom 8,16736 gold badges140 silver badges237 bronze badges 2
  • maybe slice can help you developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Vadim Hulevich Commented Jan 9, 2019 at 14:40
  • @VadimHulevich how though? calling slice on an ArrayBuffer returns another ArrayBuffer, not a SharedArrayBuffer – Tom Commented Jan 9, 2019 at 14:42
Add a ment  | 

1 Answer 1

Reset to default 8

Note that both ArrayBuffer and SharedArrayBuffer are backing data pointers that you only interact with through a typed array (like Float32Array, in your example). Array Buffers represent memory allocations and can't be "cast" (only represented with a typed array).

If you have one typed array already, and need to copy it into a new SharedArrayBuffer, you can do that with set:

// Create a shared float array big enough for 256 floats
let sharedFloats = new Float32Array(new SharedArrayBuffer(1024));

// Copy floats from existing array into this buffer
// existingArray can be a typed array or plain javascript array
sharedFloats.set(existingArray, 0);

(In general, you can have a single array buffer and interact with it through multiple "typed lenses" - so, basically, casting an array buffer into different types, like Float32 and Uint8. But you can't cast an ArrayBuffer to a SharedArrayBuffer, you'll need to copy its contents.)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744174871a4561704.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信