有一個Contextfor 向量:vecCtx它允許vector從 C 代碼訪問 Haskell 。
我需要使用多維陣列,所以vector不適合我。我更喜歡使用array. 但沒有Context它。人們是否仍然可以使用陣列,或者他們是否為陣列創建了特殊的背景關系?
uj5u.com熱心網友回復:
您可以StorableArray像這樣創建一個實體:
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Array where
import Data.Array.Storable
import Foreign.Storable (Storable)
import Language.C.Inline.Context
import System.IO.Unsafe (unsafePerformIO)
instance (Ix ix, Storable e) => VecCtx (StorableArray ix e) where
type VecCtxScalar (StorableArray ix e) = e
vecCtxLength = rangeSize . unsafePerformIO . getBounds
vecCtxUnsafeWith = withStorableArray
請注意,unsafePerformIO在這里使用是安全的,因為getBoundsfor 確實是一個純函式StorableArray。array包中沒有不可變的可存盤陣列,所以你有點被它困在一個可變的世界中,考慮到你的目標是與 C 介面,這可能沒問題。
話雖如此,我強烈建議您查看用于處理稱為massiv. 如果您嘗試一下,這里是如何VecCtx為大量可存盤的可變和不可變陣列創建實體:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Massiv where
import Data.Massiv.Array
import Data.Massiv.Array.Unsafe (unsafeWithPtr)
import Language.C.Inline.Context
instance (Index ix, Storable e) => VecCtx (Array S ix e) where
type VecCtxScalar (Array S ix e) = e
vecCtxLength = totalElem . size
vecCtxUnsafeWith = unsafeWithPtr
instance (Index ix, Storable e) => VecCtx (MArray RealWorld S ix e) where
type VecCtxScalar (MArray RealWorld S ix e) = e
vecCtxLength = totalElem . sizeOfMArray
vecCtxUnsafeWith = withPtr
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/350111.html
