Search code examples
lispcommon-lispcffi

Pass a pointer for getting result through CFFI


Here's a function in C:

union Example {
    int number;
    void *pointer;
};
void return_a_value (union Example *ptr) {
    (*ptr).number = 1;
}

Now I want to call it in Common Lisp through CFFI, how can I do it?

(defcunion Example 
  (number :int)
  (ptr :pointer))

(defcfun "return_a_value" :void
  (retval :pointer)) ; I'm not very sure here..

Solution

  • Everything's alright up to this point, including your definition of return_a_value. That's how you may call the function:

    (with-foreign-object (arg 'example)
      (setf (foreign-slot-value arg 'example 'number) 123)
      (return-a-value arg)
      (foreign-slot-value arg 'example 'number))