This is the mail archive of the guile@cygnus.com mailing list for the guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

SCM objects on the heap?


Hello!

Am I right in assuming that SCM objects are only protected from gc as long
as they are on the stack and not if they are on the heap?

example (just sketched):

SCM* p = new SCM[100];         /* C++ style, for C use malloc */
for (unsigned int i = 0; i < 100; ++i)
    p[i] = gh_cons(SCM_BOOL_T, SCM_BOOL_T);

If I am right, later accesses to p are not guaranteed to work with current
guile, since the SCM objects referencing the pairs will not be detected
during gc.

I am asking, because this can be painful if one wants to have C++ (or C)
objects generated on the heap which hold SCM data.

Assume the following scenario:

class Base
{
  public:
    virtual f1() = 0;     /* interface only */
    ...
    virtual fn() = 0;     /* interface only */
};


class Derived_C
{
    // this class provides C++ implementations of the functions f1 ... fn
};


class Derived_SCM
{
  public:
    Derived_SCM(SCM proc, SCM initial_state);

    virtual f1() { state = gh_call3(proc, symbol_f1, state); )
    ...
    virtual fn() { state = gh_call3(proc, symbol_fn, state); )

  private:
    SCM proc;
    SCM state;

    static SCM symbol_f1; // initialized to be the symbol 'f1
    ...
    static SCM symbol_fn; // initialized to be the symbol 'f1
};


With this example, every Derived_SCM object could get it's own implementation
of the functions f1 ... fn, depending of the scheme function that was passed
during construction. The scheme functions called could look like:

(define (proc method state)
  (case method
    (('f1 (perform_f1 state)))
    ...
    (('fn (perform_fn state)))))


If you are aquainted with STL classes, consider the following way of providing
an STL set of SCM objects:

------------------------------------------------------------
class SCM_smaller_p
{
  public:
    SCM_compare(SCM a_smaller_p) : smaller_p(a_smaller_p) {}
    ~SCM_compare() {}


    // This function is called to compare two elements in the set. It is
    // assumed to perform a '<' test.
    bool operator()(SCM a, SCM b) {
	return gh_call2(smaller_p, a, b) != SCM_BOOL_F;
    };

  private:
    SCM smaller_p;
};


typedef set<SCM, SCM_smaller_p> SCM_set;
------------------------------------------------------------


This way sorted sets of SCM objects could easily be generated. The sorting
predicate would be given during set construction.


If this was possible, guile could more easily be used to add flexibility to
existing programs. If not: could something be done about it?

Best regards,
Dirk Herrmann