My case is pretty simple: I have a C++ application and a Haskell library, and I just need to export from Haskell a function that would return a C string.
The issue is that the C string is originally a String
, and to get a C string out of it I need to allocate storage which will have to be explicitly deallocated (Haskell's free
or finalizerFree
, as the documentation for newCString
says).
What's a good way to handle that? Specifically I've got a few considerations:
Ideally I'd like to somehow let the Haskell runtime GC handle that, but I'm not sure how it could possibly know when and when not the memory is still needed by the foreign side. Is it possible?
If not, can I just call C's free
or is the CString
storage maintained by the Haskell runtime? if not I suppose I'll have to export Haskell's free
as-well and call it from the foreign side, correct?
Memory management is the process of controlling and coordinating a computer's main memory. It ensures that blocks of memory space are properly managed and allocated so the operating system (OS), applications and other running processes have the memory they need to carry out their operations.
As for internal memory management, Java has the best of the three, since it automates disposing of objects.
Computer programs need to allocate memory to store data values and data structures. Memory is also used to store the program itself and the run-time system needed to support it. If a program allocates memory and never frees it, and that program runs for a sufficiently long time, eventually it will run out of memory.
We can perform memory management in C++ with the use of two operators: new operator to allocate a block of memory on heap. delete operator to deallocate a block of memory from heap.
You do have to deallocate the string: as you say, there's no way Haskell's GC can know if that's still needed in the foreign side.
Haskell's free
is exactly equivalent to C's free
. You can call either, from the side you prefer.
free :: Ptr a -> IO ()
free = _free
foreign import ccall unsafe "stdlib.h free" _free :: Ptr a -> IO ()
I didn't check if this is mandated by the Haskell report + FFI Addendum, but I'd guess so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With