VASmalltalk: Cast instance of superclass to instance of subclass

I read this question today in the support forum for VASmalltalk. The poster had unchangeable source code and this source created instances of a superclass and he wanted to change those created instances to an instance of a subclass of that superclass.

I asked myself for an answer … and I did not find anything useful. In general I thought about creating a new instance of that subclass, make some copy methods to exchange the values to this new instance and finally a become: to save the references.

Then I looked at the primitive stuff of VASmalltalk and searched for a solution using that way – that need not to be a good solution – I just wanted to see, if it could be done.

I finally came up with the following solution, which will only work, if the structure between superclass and subclasses do not change.

I created a new primitive within a library with only one function:

   EsObject object = NULL;
   EsObject newClass = NULL;
   object = EsPrimArgument(1);
   newClass = EsPrimArgument(2);
   object->class = newClass;

The exported function is named “mskClassConvert” and expects two parameters: first the object to be changed and second the new class of this object.

But perhaps it could be also Object ? I’m also not sure, if the primitive code is valid for most of the classes – but perhaps not one of these Arrayed based classes

Then I needed some Smalltalk code to call this function. I created an example class “MySuperclass”.

MySuperclass >>convertTo: aClass
   ^self primConvert: self to: aClass
MySuperclass >>primConvert: anObject to: aClass
   ^self primitiveFailed

Now executing

MySuperclass new convertTo: MySubclass

returns an instance of MySubclass. If you want to have the project for Windows send me an eMail.

This entry was posted in Smalltalk and tagged , , . Bookmark the permalink.