Nasty VM stuff

Stephen Travis Pope stp at limbo.create.ucsb.edu
Tue Apr 14 12:57:06 UTC 1998


Jim B wrote,

> I would like to write some
> useful primitives. But, I have run into a couple of roadblocks...

Hey, tell me about it. Well, I promised JohnM and DanI that I'd write some doc
about writing your own prims, so here's the first installment in terms of
answers to Jim....

OK, since nobody else seems to be jumping in here to answer Jim's many questions:

Introduction: primitives written in C are essentially in a different world
altogether than the Smalltalk object space. It is possible to register
special objects and class names so that they can be accessed from C, but it's
generally not possible to "call back" i.e., to send an arbitrary Smalltalk
message from C code.


> How do I look up a name in the global space "SystemDictionary"?

Names that are to be known in the VM have to be put in a special array in
the VM. See class ObjectMemory, specialObjects array and specialObjectsOps
instVar (look at senders of splObj: and the class init code).


> How do I hash a symbol?

You don't. Create a string and return it to Smalltalk for hashing.


> How do I send it a message (including parameters)?

You return control to Smalltalk, and let Smalltalk code send messages.


> Will Mr. garbage collector collect my arguments if I pop them off the
> stack during execution of a primitive?

*Never* mess with the stack in C code. The "glue code" (a method in class
interpreter that calls the prim function and is translated into C), pops the
stack after the return from the actual C code for the primitive.


> For example, let us say that I would like to create a new rectangle
> within my primitive. 

First off, it would be *much* easier if Smalltalk passed you a rectangle and
you stuffed values into it. If you're really fixated on it, though, the
object memory class has a function instantiateClass:indexableSize:. Look at
senders of it. It assumes that class objects are registered in the special
objects array. (Point is, but Rectangle isn't, so you'd have to add it.) For my
MIDI/Sound primitives, I implemented instVarAtPut in C for integer values. 
This looks somewhat like the following:

				// memory access macro from interp.c
#define longAtput(i, val)   (*((int *) (i)) = val)

				// My own bogosity--but hey, it worx!
#define instVarAtPutInt(obj, slot, val) \
		longAtput(((char *)obj + (slot << 2)), (((int)val << 1) | 1))

This should allow you to stuff long ints into slots. 
Dealing with byte arrays is also pretty simple.
(Remember that objects have 4-byte header!)

Well, I could go on here, but will end the first installment here--stay tuned!

stp

_ Stephen Travis Pope
_ Center for Research in Electronic Art Technology (CREATE)
_ Dept. of Music, Univ. of California, Santa Barbara (UCSB)
_ stp at create.ucsb.edu,  http://www.create.ucsb.edu/~stp/





More information about the Squeak-dev mailing list