Lisp HUG Maillist Archive

FLI question: How to have C manipulate an array

Hi!

Suppose I have a C function

int foo(unsigned char *data, int len)
{
	int i;

	for (i = 0; i < len; i++)
		data[i]++;
	return len;
}

What is the recommended way to call such a thing via FLI?  This works:

(define-foreign-function (foo "foo" :source)
    ((data (:pointer (:unsigned :char)))
     (len :int))
  :result-type :int
  :language :ansi-c)

(defun call-foo (data)
  (declare (type (simple-array (unsigned-byte 8) (*)) data))
  (with-dynamic-foreign-objects ()
    (let* ((len (length data))
           (arr (allocate-dynamic-foreign-object :type '(:unsigned :char)
                                                 :nelems len)))
      (dotimes (i len)
        (declare (fixnum i))
        (setf (dereference arr :index i) (aref data i)))
      (prog1
          (foo arr len)
        (dotimes (i len)
          (declare (fixnum i))
          (setf (aref data i) (dereference arr :index i)))))))

but is there a better way (possibly one that avoids copying)?

Regards,
-- 
Nils Goesche
"Don't ask for whom the <CTRL-G> tolls."

PGP key ID 0x0655CFA0


Updated at: 2020-12-10 09:01 UTC