feeley/gambit — pull request #59 by euccastro (2013-12-24 05:37:48+00:00)
Title: Add `data` field to foreign objects.

This is analogous to the `data` field in reference counted (`___alloc_rc`ed) objects.

Rationale:
- See https://github.com/euccastro/gambit/commit/84b5375fa23a66328f8a6decd8d86a93879fa22d .
- While Gambit's ffi system is extremely versatile and powerful, there is no easy shortcut to wrapping structs and unions so they can be treated like regular Scheme objects. People have noted this before.

http://gambitscheme.org/wiki/index.php/Wish_list#FFI_Improvement

A (very preliminary) look of where I'm going with this (this code is still using an old way to create fake references between foreign objects):

https://github.com/euccastro/gambit-ffi-types

I considered and discarded the following alternatives before concluding that a change to Gambit was necessary to support this use case in a way that is robust and consistent with the rest of Gambit:

1. Using some kind of wrapper Scheme object: in order to prevent the user from too easily ending up with a reference to invalid memory, I'd have to somehow hide the underlying foreign object from them. Otherwise they could always get access to the foreign object itself and lose the wrapper. This added encapsulation would not allow the user to use "managed" foreign objects seamlessly and interchangeably with others, so no solution involving this would feel consistent with the rest of Gambit.
2. Abusing wills to create a strong reference to an object. As discussed in the gambit list [1], there is really no way to be sure when an object will never be reachable anymore.
3. Making the foreign object itself an `___alloc_rc`ed object and having its `data` field point to the object we want to keep reachable. This just begs the question: now there is no way to manage this `___alloc_rc`ed object itself without, again, adding a layer of indirection which reintroduces the problems discussed in point 1 above.