diff --git a/docs/api/cyclone/foreign.md b/docs/api/cyclone/foreign.md index ac188886..cd5182dd 100644 --- a/docs/api/cyclone/foreign.md +++ b/docs/api/cyclone/foreign.md @@ -70,7 +70,9 @@ Scheme | C `bignum` | `mp_int` `opaque` | `void *` `c-void` | `void` +`thread-data` | `gc_thread_data *` Useful notes: - Use `opaque` if you need to handle any kind of C pointer. - Use `string` to handle C `const char*` (`symbol` is strictly used to represent Scheme symbols). +- `thread-data` is a special type used to pass the current thread's `gc_thread_data` instance to a C function. Objects of this type are passed implicitly when making a Scheme function call. diff --git a/examples/ffi/sub-bignums.scm b/examples/ffi/sub-bignums.scm index 87092c61..c3870add 100644 --- a/examples/ffi/sub-bignums.scm +++ b/examples/ffi/sub-bignums.scm @@ -1,17 +1,20 @@ ;; A basic example of subtracting 2 bignums using the FFI. ;; -;; This example is notable because we need to pass the -;; current thread's data object to C so that we can pass -;; it along to functions in the Cyclone runtime. +;; This example also shows how to pass the current thread's +;; data object to C using the thread-data type specifier. +;; The thread data object is often needed so it can be passed +;; along to functions in the Cyclone runtime. ;; -(import (scheme base) (scheme write) (cyclone foreign) (srfi 18)) +(import (scheme base) (scheme write) (cyclone foreign)) (include-c-header "sub-bignums.h") -(c-define sub-big-nums bignum "sub_big_nums" opaque bignum bignum) +;; Define a C function receiving thread data and two bignum arguments +;; Note thread data is passed implicitly, so calls to sub-big-num do +;; not need to pass the thread data argument from scheme code. +(c-define sub-big-nums bignum "sub_big_nums" thread-data bignum bignum) (display (sub-big-nums - (current-thread-data) 999999999999999999999999 222222222222222222222222)) (newline) diff --git a/libs/cyclone/foreign.sld b/libs/cyclone/foreign.sld index 122c5b70..39275d59 100644 --- a/libs/cyclone/foreign.sld +++ b/libs/cyclone/foreign.sld @@ -119,6 +119,8 @@ (string-append "opaque_ptr(" ,code ")")) ((c-void) "Cyc_VOID") + ((thread-data) + "data") (else (error "scm->c unable to convert scheme object of type " ,type))))))) @@ -275,9 +277,12 @@ "(void *data, int argc, closure _, object k " (apply string-append (map - (lambda (sym/unbox) - (string-append ", object " (car sym/unbox))) - arg-syms/unbox)) + (lambda (sym/unbox type) + (if (eq? type 'thread-data) + "" + (string-append ", object " (car sym/unbox)))) + arg-syms/unbox + arg-types)) ")")) (type-checks (apply