[Haskell-cafe] FFI: how to allocate a const char * from haskell

Albert Krewinkel albert+haskell at zeitkraut.de
Tue Apr 18 16:49:04 UTC 2023


PICCA Frederic-Emmanuel <frederic-emmanuel.picca at synchrotron-soleil.fr> writes:

> Hello, I need to call a c method which take a const char *
>
> something like
>
> void hkl_holder_add_axis(const struct holder *holder, const char *name);
>
> during all the life of this object, the const char* should be accessible.
>
> So from haskell I need to create a CString which will not be affected
> by the garbage collection. The memory should be release only when the
> given object is freed. or when the program stop.
>
> when I use alloca, the memory is releases and the code segfault.
>
> I think that I could use malloc, but in that case I have a memory
> leak. (this is not that important in my case, since I create less than
> 10 of these objects).

Maybe a ForeignPtr can help here: it allows to attach a finalizer, which
you can use to free the CString once the object is GCed in Haskell.

https://hackage.haskell.org/package/base-4.18.0.0/docs/Foreign-ForeignPtr.html


-- 
Albert Krewinkel
GPG: 8eed e3e2 e8c5 6f18 81fe  e836 388d c0b2 1f63 1124


More information about the Haskell-Cafe mailing list