[Haskell-beginners] Ffi, memory allocation and failure

ch.gosch@googlemail.com ch.gosch at googlemail.com
Wed Feb 9 09:45:09 CET 2011


Dear Haskellers,
I have a question about the FFI and interfacing to C++ via C.
I want to use funcionality that I have implemented a while ago
using C++ classes, and I also see this as an exercise on how to
create wrappers using the Haskell FFI.

The class I want to wrap first is a matrix class.
Here is the thing: In order to create a matrix object, I create a C function
that calls the C++ new operator, creating a matrix object, and
returning it as a void pointer.
Deletion is handled analogously.
Then in Haskell, I import the two functions, and I have a matrix type
like this:
newtype Matrix = Matrix (Ptr Matrix)

From this I create a ForeignPtr with newForeignPtr, giving the
deletion function (which calls the C++ destructor for a matrix)
as finalizer.

Testing this showed me that it does work.
/But/: So far everything is happening in the IO monad. However, I want to
be able to work with matrices outside IO. Now, of course memory allocation
can fail, and I don't want to use something like unsafePerformIO when
there can actually be a failure when calling the constructor for a matrix.

Is there a recommended way to do this?
Also, is there a way to get memory from the Haskell runtime system in a safer
way and construct the object in that memory?

I hope I could make myself clear enough, as usual thanks for any hints!!
Christian

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110209/727154c9/attachment.htm>


More information about the Beginners mailing list