Last active
December 4, 2024 03:51
-
-
Save bencef/8f530cbdb95655547782bea98ffbb579 to your computer and use it in GitHub Desktop.
calling racket code from C lib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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