[plt-scheme] Crash when using FFI callbacks.

K.S.Sreeram sreeram at tachyontech.net
Fri Aug 10 02:41:21 EDT 2007


[PLT v370, WinXP]

Hi,

I've attached a very small C library and corresponding Scheme FFI code
which results in MzScheme crashing when using more than _one_ FFI callback.

The crash was happening at seemingly random times, until I added a call
to 'collect-garbage' in the callback procedure (as suggested by Eli
Barzilay on #scheme). Now, the crash occurs instantly.

Is there any workaround to avoid this crash? Or am I using the FFI
library incorrectly?

Thanks in advance!
[sreeram;]
-------------- next part --------------
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int value;
} foo_t;

typedef void (*foo_callback_t)(foo_t *foo);

typedef struct _callback_node_s callback_node_t;

struct _callback_node_s {
    foo_callback_t callback;
    callback_node_t *next;
};

static callback_node_t *callback_list = NULL;

void add_foo_callback(foo_callback_t callback)
{
    callback_node_t *node = malloc(sizeof(callback_node_t));
    node->callback = callback;
    node->next = callback_list;
    callback_list = node;
}

void notify_once()
{
    foo_t foo;
    callback_node_t *node;

    foo.value = 10;
    for (node = callback_list; node != NULL; node = node->next)
        node->callback(&foo);
}

void notify_n_times(int n)
{
    int i;

    for (i = 0; i < n; ++i)
        notify_once();
}
-------------- next part --------------
mylib.dll: mylib.c
	gcc -shared -o mylib.dll mylib.c

clean:
	rm -f mylib.dll
-------------- next part --------------
(module mylib mzscheme
  (require (lib "foreign.ss"))
  (unsafe!)

  (provide
   add-foo-callback
   notify-once
   notify-n-times
   )

  (define mylib-lib (ffi-lib "mylib"))

  (define _foo-callback (_fun _pointer -> _bool))

  (define add-foo-callback (get-ffi-obj "add_foo_callback" mylib-lib
                                        (_fun _foo-callback -> _void)))

  (define notify-once (get-ffi-obj "notify_once" mylib-lib
                                   (_fun -> _void)))

  (define notify-n-times (get-ffi-obj "notify_n_times" mylib-lib
                                      (_fun _int -> _void))))
-------------- next part --------------
(require "mylib.ss")

(define (my-callback foo)
  (display "callback notified") (newline)
  (collect-garbage)
  #f)

(define (main)
  (add-foo-callback my-callback)
  (add-foo-callback my-callback)
  (notify-n-times 10))

(main)


More information about the plt-scheme mailing list