Use another language to call a function: Difference between revisions

→‎{{header|Racket}}: New Racket solution
(Nimrod -> Nim)
(→‎{{header|Racket}}: New Racket solution)
Line 817:
$
</lang>
 
=={{header|Racket}}==
 
Since this problem is presented as the inverse to [[Call foreign language function]], I've focused on just demonstrating a callback from C into Racket, instead of showing how to [http://docs.racket-lang.org/inside/embedding.html embed the whole Racket runtime into C].
 
Starting with the given C code, modify it so that <tt>Query</tt> is a variable instead of an external:
 
<lang C>
typedef int strfun (char * Data, size_t * Length);
strfun *Query = NULL;
</lang>
 
The rest of the C code is left as-is. Compile it into a dynamic library, then run the following Racket code:
 
<lang racket>
#lang racket
 
(require ffi/unsafe)
 
(define xlib (ffi-lib "./x.so"))
 
(set-ffi-obj! "Query" xlib (_fun _pointer _pointer -> _bool)
(λ(bs len)
(define out #"Here I am")
(let ([bs (make-sized-byte-string bs (ptr-ref len _int))])
(and ((bytes-length out) . <= . (bytes-length bs))
(begin (bytes-copy! bs 0 out)
(ptr-set! len _int (bytes-length out))
#t)))))
 
((get-ffi-obj "main" xlib (_fun _int (_list i _bytes) -> _void))
0 '())
</lang>
 
Note that this code is intentionally in a simple low-level form, for example, it sets the pointer directly instead of using a C function.
 
The output is the expected “<tt>Here I am</tt>” line.
 
=={{header|Tcl}}==