简体   繁体   English

如何在GHCJS上从Unboxed Vector转换为JS TypedArray?

[英]How do you convert from an Unboxed Vector to a JS TypedArray on GHCJS?

I have an element of type Data.Vector.Unboxed.Vector Word32 . 我有一个Data.Vector.Unboxed.Vector Word32类型的元素。 I want to convert that to a native JS TypedArray (an Uint32Array , specifically). 我想将其转换为本机JS TypedArray (特别是Uint32Array )。 I'm aware of toJsArray and toJsValListOf , but both functions deal with lists, not vectors, and are inefficient. 我知道toJsArraytoJsValListOf ,但两个函数都处理列表,而不是向量,并且效率低下。 How can I convert an unboxed Vector directly to a JS TypedArray ? 如何将未装箱的Vector直接转换为JS TypedArray

I was able to solve this up to marshalling to an Int32Array instead of an Uint32Array ; 我能够解决这个问题,然后编组到Int32Array而不是Uint32Array ; probably someone who has actually known GHCJS for more than the one hour I've put into this will be able to expand on this so that you get your Uint32Array (or you can just make a hacked-up version of GHCJS.Buffer that supports a getUint32Array operation). 可能有人已经知道GHCJS超过一小时我已经投入使用这个将能够扩展到这一点,以便你得到你的Uint32Array (或者你可以制作一个GHCJS.Buffer -up版本的GHCJS.Buffer支持一个getUint32Array操作)。

The idea is to get the ByteArray underlying the Vector representation, and then slice it so that only the relevant portion remains: 我们的想法是让ByteArray成为Vector表示的基础,然后将其slice以便只保留相关部分:

import Data.Vector.Unboxed as V
import Data.Word

import qualified Data.Vector.Unboxed.Base as B
import qualified Data.Vector.Primitive as P
import GHCJS.Types
import qualified GHCJS.Buffer as Buffer
import JavaScript.TypedArray (Int32Array)

-- TODO: generalize this to all types that support unboxed vectors...
toI32Array :: Vector Word32 -> Int32Array
toI32Array (B.V_Word32 (P.Vector offset len bs)) =
    js_slice offset (offset + len) $ Buffer.getInt32Array (Buffer.fromByteArray bs)


foreign import javascript unsafe "$3.slice($1, $2)" js_slice :: Int -> Int -> Int32Array -> Int32Array
-- should be
-- foreign import javascript unsafe "$3.slice($1, $2)" js_slice :: Int -> Int -> SomeTypedArray a m -> SomeTypedArray a m
-- but alas, JavaScript.TypedArray.Internal.Type is a hidden module

Here's some example code using it: 以下是使用它的一些示例代码:

v :: Vector Word32
v = V.fromList [1, 2, 3]

foreign import javascript unsafe "console.debug($1);" js_debug :: JSVal -> IO ()

main = do
    let v' = toI32Array v
    js_debug $ jsval v'

If you look at the console in a browser, you can check that jsval v' does indeed have type Int32Array . 如果你在浏览器中查看控制台,你可以检查jsval v'确实有Int32Array类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM