Marko Rauhamaa <[email protected]> writes:
> [email protected] (Ludovic Courtès):
>
>> I’m very skeptical about this use case (I’d use ‘mmap’ and get a
>> bytevector.)
>
> Please elaborate.
>
> 1. Does Guile offer mmap to Scheme code?
It's pretty easy to call C functions from Scheme. Here's a trivial
example.
$ cat map_file.c
#include <stddef.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
void *map_file(char *file) {
int fd = open(file, O_RDONLY);
off_t size = lseek(fd, 0, SEEK_END);
return mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
}
$ gcc -shared -o map_file.so -fPIC map_file.c
$ guile
)> ,use (system foreign)
)> (define map-file
(pointer->procedure
'*
(dynamic-func "map_file"
(dynamic-link "./map_file"))
(list '*)))
)> (define file-ptr (map-file (string->pointer "/home/taylan/todo")))
)> (define file-bv (pointer->bytevector file-ptr 100)) ;see note below
)> file-bv
$3 = #vu8(45 42 45 32 111 114 103 32 45 42 45 10 10 ...)
That's ASCII for "-*- org -*-\n\n", which is what my todo file begins
with. :-)
(It's a file mode marker for Emacs, for those who don't know.)
Note: The second argument to pointer->bytevector defines the size of the
bytevector. I passed 100 because I was too lazy to get the size of the
file. You should pass the size of the file in bytes.
> 2. What would prevent Guile's GC from scanning the mmapped area for
> pointers?
I don't know the details but AFAIK this is no problem with Boehm GC.
> 3. How do I efficiently encode information in a bytevector in Scheme
> code?
What sort of data?
I have a library called bytestructures that imitates the C type system
within Scheme, to be used on bytevectors that contain data structures
generated by C code, though the library is built upon a generic core
with which other structures can be declared as well. Not sure if this
helps you:
https://github.com/TaylanUB/scheme-bytestructures/
> Marko
Hope I could help,
Taylan