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 <chicken-users@nongnu.org>:

> 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
>
>

Reply via email to