Use another language to call a function: Difference between revisions

→‎Using cptr and memcpy: Show C side-by-side.
(→‎{{header|TXR}}: Break into sections; add cptr-memcpy based solution.)
(→‎Using cptr and memcpy: Show C side-by-side.)
Line 1,177:
(deffi-cb query-cb int (cptr (ptr (array 1 size-t))))
(query (query-cb (lambda (buf sizeptr) ; int lambda(void *buf, size_t *sizeptr)
(symacrolet ((size [sizeptr 0])) ; { #define size sizeptr[0]
(let* ((s "Here am I") ; char *s = "Here am I";
(l (length s))) ; size_t l = strlen(s);
(cond ; if (length > size)
((> l size) 0) ; { return 0; } else
(t (memcpy buf s l) ; { memcpy(buf, s, l);
(set size l)))))))) ; return size = l; } }</lang>
 
Here, the use of the <code>str</code> type in the <code>memcpy</code> interface means that FFI automatically produces a UTF-8 encoding of the string in a temporary buffer. The pointer to that temporary buffer is what is passed into <code>memcpy</code>. The temporary buffer is released after <code>memcpy</code> returns.
 
To reveal the similarity between the Lisp logic and how a C function might be written, the corresponding C code is shown.
However, that C code's semantics is, of course, devoid of any hidden UTF-8 conversion.
 
=={{header|zkl}}==
543

edits