[MacRuby-devel] patterns in high-level [Ruby] wrappers for [C] APIs

Ernest N. Prabhakar, Ph.D. prabhaka at apple.com
Thu Feb 11 12:25:29 PST 2010


Hi Rich,

On Feb 9, 2010, at 4:23 PM, Rich Morin wrote:
> Unfortunately, I don't have any specific patterns of my own to offer, as
> yet.  So, I'm hoping that Rich and Ernie might be willing to tell the rest
> of us about their approaches and rationales.  

Interesting.

For what it's worth, here's the process I've ended up following for GCD.  Note that I didn't really start out with this plan, it largely emerged as I went along

http://svn.macosforge.org/repository/ruby/MacRuby/trunk/gcd.c

A. Create a thin veneer that "almost" matches the underlying C API - except:
	1. Turn data structures into true objects, and their functions into methods
	2. Map underlying memory management to Ruby garbage collection
	3. Prevent Ruby code from ever creating hard C crashes
	4. Take advantage of optional arguments to reduce API "noise"
	5. Namespace constants
	6. Where possible, combine related methods together to prevent sequencing errors

The last is the most controversial. In this particular case, I implemented GCD sources in a way that automatically configures them during "new", which is much simpler but also reduces flexibility. I am fairly (but not 100%) certain that this handles all the common cases, so I believe it an acceptable tradeoff -- but I could be wrong.

http://svn.macosforge.org/repository/ruby/MacRuby/trunk/lib/dispatch/

B.  Create a high-level convenience API that:
	1. Encapsulates common design patterns
	2. Hides infrequently used options behind default arguments
	3. Provides Ruby idioms and duck-types
	4. Allows trivial invocation of the most common cases

The jury is still out on whether I've succeeded, but my initial attempts to use the API to implement itself are promising.

> I'd also like to hear about other projects (and notions) in this area.

I assume you're familiar with Ruby FFI?  Worth asking over there, as presumably they've wrestled with this issue before...

Hope this helps,
-- Ernie P.






More information about the MacRuby-devel mailing list