LispWorks Foreign Language Interface User Guide and Reference Manual > 4 Advanced Uses of the FLI > 4.2 Modifying, passing and returning strings

NextPrevUpTopContentsIndex

4.2.5 Calling a C function that takes an array of strings

Suppose you have a C function declared like this:

extern "C" void foo( const char** StringArray);

To call this from Lisp you need to first allocate the foreign memory for each piece of data, that is the array itself and each string. Assuming that foo does not capture any of the pointers, you can give this memory dynamic extent as follows:

(defun convert-to-dynamic-foreign-array (strings)
  (let* ((count (length strings))
         (array
          (fli:allocate-foreign-object
           :nelems (1+ count) ; assume NULL terminated
           :type '(:pointer :char))))
    (dotimes (index count)
      (setf (fli:dereference array :index index)
            (fli:convert-to-dynamic-foreign-string
             (elt strings index))))
    (setf (fli:dereference array :index count) nil)
    array))
 
(fli:define-foreign-function (%foo foo)
    ((string-array (:pointer (:pointer :char)))))
(defun foo (strings)
 
  (fli:with-dynamic-foreign-objects ()  ; provide a dynamic scope
    (%foo (convert-to-dynamic-foreign-array strings))))

LispWorks Foreign Language Interface User Guide and Reference Manual - 21 Dec 2009

NextPrevUpTopContentsIndex