Skip to content

Instantly share code, notes, and snippets.

@bencef
Last active April 8, 2017 18:04
Show Gist options
  • Save bencef/8f530cbdb95655547782bea98ffbb579 to your computer and use it in GitHub Desktop.
Save bencef/8f530cbdb95655547782bea98ffbb579 to your computer and use it in GitHub Desktop.
calling racket code from C lib
#lang racket
(require
ffi/unsafe
ffi/unsafe/define)
;; helper to define racket symbols to refer to C symbols
(define-ffi-definer my-define (ffi-lib "libmyprint"))
;; typedef. this corresponds to the argument type of my_print
(define _my-callback (_cprocedure (list _string) _string))
(my-define my_print (_fun _my-callback -> _string))
;; racket function which will be passed to c code as a callback
;; returns a string of the first character of its input concatenated
;; four times
(define (four-times-the-first str)
(make-string 4 (string-ref str 0)))
;; call the C function with our callback
;; output should be "CCCC"
(my_print four-times-the-first)
CFLAGS=-fPIC
CC=cc
all: libmyprint.so
clean:
rm -f *.o *.so
libmyprint.so: myprint.o
${CC} ${CFLAGS} -shared -o libmyprint.so myprint.o
myprint.o: myprint.c
${CC} ${CFLAGS} -c myprint.c
#include <stdio.h>
typedef char*(*callback)(char*);
char *
my_print(callback cb)
{
static char text[] = "Cat";
return cb(text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment