guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Foreign wrapped C structures and guardians


From: Daniel Hartwig
Subject: Re: Foreign wrapped C structures and guardians
Date: Tue, 24 Jul 2012 11:16:28 +0800

Hello

On 23 July 2012 21:59, Patrick Bernaud <address@hidden> wrote:
> Hello,
>
> I am trying to create and manipulate some C structures with the
> foreign interface of Guile 2.0. This is part of an extension to an
> existing application.

Your best option is to handle the low-level allocation and
manipulation of these structs from the c side, exposing the
appropriate functions to scheme.  Your scheme code then treats the
pointers as opaque objects and does not directly manipulate the
memory:

(use-modules (my-struct)) ;; make-my-struct, my-struct->list
(use-modules (system foreign))
(define l 10)
(define x (make-my-struct (iota l))
(define a (pointer-address x))
(set! x #f)
(define (dump-struct)
  (write (my-struct->list (make-pointer a))) (newline))

The procedure define-wrapped-pointer-type is useful for this.

> How to make a structure created with 'make-c-struct' permanent? That
> is avoiding garbage collection and then letting the application, not
> Guile, ultimately taking care of its memory.

Your guardian test should work but on my system it is broken also.

The libguile function scm_malloc will allocate memory that the
collector avoids.  You can then copy the data to this:

(define malloc
  (let ((this (dynamic-link)))
    (pointer->procedure '*
                        (dynamic-func "scm_malloc" this)
                        (list size_t))))
(define memcpy
  (let ((this (dynamic-link)))
    (pointer->procedure '*
                        (dynamic-func "memcpy" this)
                        (list '* '* size_t))))
(define l 10)
(define s (make-list l int))
(define x (malloc (sizeof s)))
(define a (pointer-address x))
(memcpy x (make-c-struct s (iota l)) (sizeof s))

But this is an extra malloc and memcpy which could be avoided if you
implement the allocator in c.

>
> I tried with guardians but the memory still seems to be overwritten
> from time to time. For example, with the script attached, here is what
> I get:
>
>   $ guile --no-auto-compile -s test.scm
>   (0 1 2 3 4 5 6 7 8 9)
>   (0 1 2 3 4 5 6 7 8 9)
>   (80 62 102 97 107 101 60 47 80 62)

Although the guardian should be protecting this, it does appear not to
in your test.scm.  If I use --fresh-auto-compile it works fine.

$ /usr/bin/guile --version | sed 1q
guile (GNU Guile) 2.0.6

Regards



reply via email to

[Prev in Thread] Current Thread [Next in Thread]