Let’s say there is a C function:
int do_something(int *output);
I can define it in lisp with cffi like this:
(cffi:defcfun ("do_something" %do-something)
:int
(output :pointer))
How can I call it and get the value of output? I have looked at other questions, but these are dealing with structs or unions, both of which do not apply in my case.
In your answer you probably have a memory leak because the allocated memory is never freed. See
cffi:foreign-freewhich is used to "Free a PTR allocated by FOREIGN-ALLOC.". Typically you can useunwind-protectto callforeign-free:Alternatively, you can use the following macro:
Note that if you expand the macro it seems to be able to allocate memory on the stack (tested with SBCL), unlike the above version with
foreign-allocandforeign-free. I think these two functions are best used in cases where the lifetime of the object is more complex than what a lexical scope offers.