Re: Recursion in foreign-safe-lambda

Thomas Chust via Chicken-users <[email protected]>
Newsgroups gmane.lisp.scheme.chicken
Message-ID <CAEOXGfyR-A4if+3mogr8rHXfLO27tCszyvaXCg5vJKhL_amEYw@mail.gmail.com>
Hello Massimo,

I believe you can only allocate Scheme data from a foreign-primitive, not
from a foreign[-safe]-lambda: The memory reserved by C_alloc lives *on the
C stack*, so a C function that uses this primitive must never return. It
can invoke a continuation to communicate a return value, but it must not
unwind the C stack below the point of allocation.

There is nothing preventing such a function from invoking itself, though.
As long as the recursive call is either optimized away as a simple jump or
never returns, the allocation should still work!

Ciao,
Thomas C.


Am Sa., 20. Sept. 2025 um 18:27 Uhr schrieb Massimo Nocentini via
Chicken-users <[email protected]>:

> Dear list,
>
> I have a question about the foreign module. Given the following definition:
>
> (define parse (foreign-safe-lambda* scheme-object (((const c-string)
> filename))
> "C_word out = P(filename); C_return(out);"
> ))
>
> and
>
> extern C_word P(const char *filename)
> {
> char* str = "hello world";
> int length = strlen(str);
> C_word* ptr = C_alloc (C_SIZEOF_STRING (length));
> C_word res = C_string (&ptr, length, str);
> return res;
> }
>
> When I use the parse function on a string, I get the following output:
> #(#<procedure> #<procedure C_values> (#(#<procedure> #...
> How can I allocate Scheme object from a C function (possibly recursive)?
> Thank you all in advance,
> Massimo
>
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.