I guess I have a simple problem, but I'm not able to solve it: I want to create a vector, call FFI on this vector and return it.
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
withCarray :: Int -> (Ptr Float -> IO ()) -> (Vector Float)
withCarray n f = VS.create $ do
v <- VSM.new n
VSM.unsafeWith v f
return v
Now, VSM.unsafeWith returns an IO, and this is in the ST Monad. But if I use ioToST or liftIO I get the following problem:
Couldn't match type ‘s’ with ‘RealWorld’
‘s’ is a rigid type variable bound by
a type expected by the context:
forall s. ST s (VSM.MVector s Float)
at src/Interpolation.hs:(60,30)-(63,10)
Expected type: ST s (VSM.IOVector Float)
Actual type: ST s (VSM.MVector (PrimState (ST s)) Float)
Any idea, how I can convert the unsafeWith
to the correct Monad? I saw that IO and ST are both Prim-Monads, so it should be possible to convert them, right?
unsafeIOToST
. Whether this is remotely sensible depends heavily on what your FFI is actually doing, and I'm too sleepy right now to even guess whether it might be reasonable in the context of your code.IO
andST
. InsideIO
, you can perform anything (e.g. sending an email, launching missiles, ...) whileST
guarantees that no I/O is performed except for mutatingST
references and vectors. If you are sure that the FFI call is not doing anything (including reading from disk/network) beyond mutating the vector, thenunsafeIOToST
can be used. Calling such an unsafe function puts the burden on you to verify this is the case.