Download CFFI User Manual

Transcript
Chapter 4: An Introduction to Foreign Interfaces and CFFI
13
If we are supposed to keep the C string around, but it goes away, what happens when
some libcurl function tries to access the URL string? We have reentered the dreaded world
of C “undefined behavior”. In some Lisps, it will probably get a chunk of the Lisp/C stack.
You may segfault. You may get some random piece of other data from the heap. Maybe,
in a world where “dynamic extent” is defined to be “infinite extent”, everything will turn
out fine. Regardless, results are likely to be almost universally unpleasant.7
Returning to the current set-curl-option-url interface, here is what we must do:
(let (easy-handle)
(unwind-protect
(with-foreign-string (url "http://www.cliki.net/CFFI")
(setf easy-handle (curl-easy-init))
(set-curl-option-url easy-handle url)
#|do more with the easy-handle, like actually get the URL|#)
(when easy-handle
(curl-easy-cleanup easy-handle))))
That is fine for the single string defined here, but for every string option we want to pass, we
have to surround the body of with-foreign-string with another with-foreign-string
wrapper, or else do some extremely error-prone pointer manipulation and size calculation
in advance. We could alleviate some of the pain with a recursively expanding macro, but
this would not remove the need to modify the block every time we want to add an option,
anathema as it is to a modular interface.
Before modifying the code to account for this case, consider the other reason we can’t
simply use :string as the foreign type. In C, a char * is a char *, not necessarily a string.
The option CURLOPT_ERRORBUFFER accepts a char *, but does not expect anything about
the data there. However, it does expect that some libcurl function we call later can write
a C string of up to 255 characters there. We, the callers of the function, are expected to
read the C string at a later time, exactly the opposite of what :string implies.
With the semantics for an input string in mind — namely, that the string should be
kept around until we curl_easy_cleanup the easy handle — we are ready to extend the
Lisp interface:
(defvar *easy-handle-cstrings* (make-hash-table)
"Hashtable of easy handles to lists of C strings that may be
safely freed after the handle is freed.")
(defun make-easy-handle ()
"Answer a new CURL easy interface handle, to which the lifetime
of C strings may be tied. See ‘add-curl-handle-cstring’."
(let ((easy-handle (curl-easy-init)))
(setf (gethash easy-handle *easy-handle-cstrings*) ’())
easy-handle))
(defun free-easy-handle (handle)
7
“But I thought Lisp was supposed to protect me from all that buggy C crap! ” Before asking a question
like that, remember that you are a stranger in a foreign land, whose residents have a completely different
set of values.