gauche.ffi - FFI ¶This module provides the means to call compiled functions in other langauges via C ABI. It allows user programs to use external libraries without writing a custom extension.
Although it is convenient, you need to keep in mind that the external libraries does not necessarily aligns Gauche’s runtime conventions, therefore you cannot rely on Gauche’s guardrails. You can easily pass arguments of incorrect types, interpret the result incorrectly, or access objects outside of its lifetime. Small mistakes can eaisly cause access violation or memory corruption.
We adopt pluggable subsystems; you can choose the underlying FFI layer
depending on the architecture and your particular needs.
For the time being, stubgen subsystem is available on
all the architecture, and native subsystem on x86_64 with
with Unix-like systems and MinGW/Windows. Native subsytem will
be enhanced to Aarch64 soon.
The code that uses FFI looks like the following:
(use gauche.ffi) (use gauche.native-type) (with-ffi (dynamic-load "/path/to/library") () ;; Define C functions and callbacks (define-c-function foo '(int c-string) 'int) ... ) ;; Call the defined C function (foo 4 "bar")
Foreign functions are defined within the form ‘with-ffi‘. Inside the form, you can define C functions and C callbacks. The defined C functions are visible from the rest of the code, and you can call it as a Scheme function.