free-foreign-object vs. free Issues

Martin Ginkel <[email protected]> Mon, 30 Aug 2004 09:46:07 +0200
Newsgroups gmane.lisp.uffi.devel
Organization MPI Magdeburg, Germany
Message-ID <[email protected]>
Dear all,

I wrapped a larger C-library using uffi, which worked mostly fine.
But there is an issue with c-functions, that return freshly
allocated C-strings. I have some of them, that allocate memory on
the C-heap and expect the caller (Lisp) to free the string when appropriate.

In the doc of uffi this case is described:
http://uffi.b9.com/manual/strings.html
I tried the free-foreign-object on the string, and it worked fine in
CMUCL. But in Allegro (6.2-linux) it apparently doesn't free anything,
but also does not throw an error.
The solution was to use the "free" from libc after converting the
string.

In my opinion the model behind this could be:
If you allocate a foreign object in Lisp and give it to C, you should
free this with free-foreign-object. At least in Allegro this seems to
work in a different heap space. But if C has allocated something, you
should free with libc::free.
Are there Issues with using libc directly in other Platforms?

	CU
	Martin


Example:

(uffi:def-function ("free" uffi::c-free)
     ((o :pointer-void))
   :returning :void)

;; Function char* SBML_formulaToString(void* tree)
(uffi:def-function ("SBML_formulaToString" sbml-formula-to-string1866)
                    ((tree :pointer-void)) :returning :pointer-void)

(cl:defun sbml-formula-to-string (tree)
   (cl:let (res1867)
     (cl:unwind-protect
         (cl:progn (cl:setq res1867 (sbml-formula-to-string1866 tree))
                   (uffi:convert-from-foreign-string res1867))
       (cl:when res1867 (uffi::c-free res1867)))))




-- 
+-[Martin Ginkel]-------------[mailto:mginkel(at)mpi-magdeburg.mpg.de]-+
| MPI Magdeburg, Zi S2.09    Sandtorstr. 1, D-39106 Magdeburg, Germany |
| There are only 10 kinds of people in the world:  those understanding |
| binary and those who don't.                                          |
+-[tel/fax: +49 391 6110 482/529]----[http://www.mpi-magdeburg.mpg.de]-+