The Do-It Yourself Guide to Squeak Primitives


2. Design the Smalltalk Interface

The first step in the coding is to determine what the Smalltalk side of the primtive should look like. This means designing the signature (i.e., the receiver, arguments, and return value) of the high-level method that expands into the primitive call.

For the purposes of this example, I'll take a method from the Siren/Squeak MIDI I/O interface. This is the input primitive that reads a MIDI data packet from the OS-level driver. The details are moot for this presentation.

I have a class MIDIPacket that has inst. vars. as shown in the following definition.

	Object subclass: #MIDIPacket
		instanceVariableNames: 'length time flags data '
		...

The first three inst. vars. are integers, the last is a ByteArray (which is pre-allocated to 3 bytes--the max size of normal MIDI messages [system exclusive packets are handled specially]).

The primitive will live in class PrimMIDIPort and will take a MIDIPacket and pass it down to the VM, who will fill it in with data read from the MIDI driver. The primitive returns the number of bytes read (the length inst. var. of the packet). Since the primitive does not use the state of its receiver, it could be put in just about any class. The argument is the important component.

So, the primitive method will look like,

    PrimMIDIPort >> primReadPacket: packet data: data

I pass the packet object and the data byte array separately for simplicity of the C code and for flexibility (in case I decide to split them into two Smalltalk objects in the future). It's also easier to decompose an object in Smalltalk than it is in C.