The Do-It Yourself Guide to Squeak Primitives


5. Write the Smalltalk Primitive method

This is the actual link to the VM primitive. You need to pick an unassigned primitive number (in the Interpreter class's PrimitiveTable); I found that 614 was free (I had already used 610-613 for useless drivel). In class PrimMIDIPort, I added the following method,

primReadPacket: packet data: data
	"Read a packet from the MIDI driver."
	"Write data into the arguments; answer the number of bytes read."

	<primitive: 614>
	self error: 'MIDI read failed.'

The "<primitive: XXX>" construct is a primitive call--it's Smalltalk's way of "trapping" into the VM. The body of the method is the primitive. The primitive number (614) is an index into the table of all primitives that's in the Interpreter class.

If the primitive returns successfully, the statements that follow the primitive call will not be executed. On the other hand, if the primitive fails, the Smalltalk code that follows the primitive call will be executed. This is quite hand for cases where you want to try a Smalltalk implementation (i.e., a good number of primitives fail if the arguments are not of the default types), or re-try the primitive with different arguments (i.e., coerce one of the arguments and re-send the method).

The return value from the primitive (actually, the thing left on the top of the stack by the glue code--see below) will be the return value of this method.