I've experimented in the past with making a macro that would generate the appropriate ffi code to create and manage c structs/unions/types. The challenge was to handle references obtained from accessors to fields containing other structs/union/types within them in such a way that
- no copying was necessary, and
- the original structure wouldn't be released as long as derived references existed.
For example, to handle events in SDL you create a SDL_Event union that you pass to functions to query for events. When the data for a particular event is populated, you query the type with evt.type and then access the fields of the specific type by accessing evt.key, a "view" on the same structure of type SDL_KeyboardEvent. There is no point in copying the structure when you do this. Also, you don't want the SDL_Event to be released while you're using (holding a reference to) the SDL_KeyboardEvent. While in this case it's not hard to manually keep the parent object alive, in the general case it feels more schemey to let the garbage collector take care of that.
What I came up with at that time was not legible and I'm not proud of it. While it seemed to work in my x64 machine, I got a segmentation fault when running the tests in a x86 installation:
https://github.com/euccastro/gambit-SDL2/blob/master/ffi-macro.scm