Tony, First of all, take some time and browse through some of the various eggs that interface to foreign code, for example anything by Felix, Thomas or Kon. Although the manual contains all the technical details, for practical implementation it is best to pore through existing code to get a feel for the idioms and maybe comments on design decisions. The allocation method you choose will depend on what exactly you're trying to do (if you have a concrete example, post it here and we can offer some advice on that).
Briefly, the two ways you would normally do this are: allocate on the C stack in C, and allocate a Scheme object in Scheme and pass it to the C function. You mentioned both constructing a Scheme object and allocating a foreign record, so it's not clear what your goal is. You may allocate relatively moderate amounts of data on the C stack and then "return" it if your function is declared as foreign-primitive. (It is not "returned" but rather "passed forward" in CPS--no stack unwind is done.) For example, you could generate a vector, or convert an C array of ASCIIZ strings to a vector of Scheme strings. You may also, if you know the size of a piece of foreign data ahead of time, allocate a scheme object (for example, via make-byte-vector) and pass that as a parameter to the C function. You would do this when the C code needs to write to a C structure that you are making available to Scheme (for example, the dst result of inet_pton(af, src, dst) ). There are some other advanced methods of allocation, some of which have been mentioned on this list over time, but I have found these two almost always suffice. On 1/22/07, Tony Sidaway <[EMAIL PROTECTED]> wrote:
As I understand it, Chicken's design means that structures are allocated on the C stack frame, so for instance I could use C_alloc() and various C macros such as C_vector() to allocate a Scheme object on the C stack and it would be subsequently usable in Scheme code, but this would only be useful for callbacks, because the data is reclaimed by the normal stack unwind when the foreign (C) function returns.
A cleaner way is to rewrite the code so that the foreign data structure is declared as a foreign-record and allocated (on the C heap) in Scheme code prior to the C call. Appropriate use of set-finalizer! ensures that the allocated heap memory is freed when the associated (enclosing) Scheme object is about to be reclaimed by garbage collection. This is also pretty efficient because the data structure is controlled by malloc() and free() and there is no run-time impact on the C code, which simply works on the allocated C structure.
_______________________________________________ Chicken-users mailing list [email protected] http://lists.nongnu.org/mailman/listinfo/chicken-users
