dynamic reloading added by megane on Thu Jun 16 17:41:03 2011


File: testlib.scm
-----

(module
    testlib
    ()
    (reexport testlib-c) ;; <- This shouldn't be reloaded dynamically
    )


File: test.scm
-----

(include "testlib_c")
(include "testlib")

(module
 test
 *
 (import chicken scheme)
 (import foreign)
 (import testlib)
 (use srfi-4)
 (use srfi-1)
 (use lolevel)

 (let-location
  [(arrpointer (c-pointer int))]
  (let* [(n (my-function (location arrpointer)))
	 (vec (make-s32vector n 1))]
    (C-memcpy (make-locative vec)
	      arrpointer
	      (* n (foreign-value "sizeof(int)" size_t)))
    (print vec)))

 (define dyn-reload
   (lambda ()
     (print)
     (print "Doing dynamic reload...")
     (load "testlib")
     (import testlib)
     (print "dynamic reload complete")))

 (dyn-reload))


File: Makefile
-----

CSC=csc
CSCCC=$(CSC) -static-extension chicken-syntax -debug-level 2 -include-path . -debug F
CSCLD=$(CSC)

TARGETS=\
	main

all: $(TARGETS)

lib:
	gcc -c testlib_c.c

main: clean lib
	$(CSCCC) -o main test.scm -L testlib_c.o

clean:
	rm -f main *.o



File: testlib_c.c
-----

#include <stdlib.h>
#include <stdio.h>

int *myarray = NULL;
int inited = 0;

int my_function(int *retarr) {
  if (0 == inited) {
    myarray = (int*) malloc(10 * sizeof(int));
    inited = 1;
  }
  int amt = 1 + (int)(rand() % 9);
  int i;
  for(i=0; i < amt; i++) {
    myarray[i] = (int)(rand() % 100);
    printf("%d: %d\n", i, myarray[i]);
  }
  
  *retarr = (int)myarray;
  return amt;
}



File: testlib_c.scm
-----

(module
 foo-testlib
 *
 (import chicken scheme)
 (import foreign)
 (use srfi-4)
 (use srfi-1)
 (use lolevel)

 (define-foreign-type size_t int)
 (define my-function (foreign-lambda int "my_function" (c-pointer int)))
 
 (foreign-declare "#include <string.h>")
 (define C-memcpy (foreign-lambda void "memcpy" (c-pointer void) (c-pointer void) size_t)))

(module testlib-c ()
	(reexport foo-testlib))

-------------------------------------------------------------
Example output:
0: 20
1: 27
2: 20
3: 55
4: 21
5: 73
6: 91
#s32(20 27 20 55 21 73 91)

Doing dynamic reload...

Error: (reexport) during expansion of (reexport ...) - cannot import from undefined module: testlib-c

	Call history:

	print		
	test#dyn-reload		
	print		
	print		
	load		
	<syntax>		(module testlib () (reexport testlib-c))
	<syntax>		(##core#module testlib () (reexport testlib-c))
	<syntax>		(reexport testlib-c)	<--