Code archives/Miscellaneous/Object Allocation & Type Changing

This code has been declared by its author to be Public Domain code.

Download source code

Object Allocation & Type Changing by N2009
You probably looked at the title and went "isn't that what an array is for?" You'd be wrong. Although I suppose you could allocate an array using this, it would probably crash whenever you used it next. What this does is sort of the same thing as what BMax does when it allocates a type, only you get to specify the size of an instance rather than just specifying the type.

Additionally, the SwapClass function lets you change the type of the object at runtime - it's all fairly basic, you should have no trouble understanding it after a quick glance at blitz_object.h. I suppose, at the very least, this might make you understand the structure of BMax objects (except arrays and strings, which require more explanation than "look at blitz_object.h" since the both are a little different).
SuperStrict

Private

Extern "C"
	Function bbGCAlloc:Byte Ptr Ptr(sz:Int, clas:Byte Ptr)
End Extern

Function _SwapClass:Byte Ptr(p:Byte Ptr Ptr, newtype:TTypeID)
	Assert p Else "No object provided"
	Assert newtype Else "No TTypeID provided"
	Local old_class:Byte Ptr = p[0]
	p[0] = Byte Ptr(newtype._class)
	Return old_class
End Function

Function _AllocateObject:Byte Ptr Ptr(size:Int, initType:TTypeID)
	If initType = Null Then
		initType = ObjectTypeID
	EndIf
	
	size :+ 8
	Assert size >= 8 Else "Invalid size for object"
	
	If size < initType._size+4 Then
		size = initType._size+4
	EndIf
' Allocate object
	Local p:Byte Ptr Ptr = bbGCAlloc(size, Byte Ptr(initType._class))
' Get constructor for initial type	
	Local clas:Byte Ptr Ptr = Byte Ptr Ptr(initType._class)
	Local _new(obj:Byte Ptr Ptr)=clas[4]
	clas = Byte Ptr Ptr(clas[0])
	
	While clas <> Null And Int(Byte Ptr(_new)) = 0
		clas = Byte Ptr Ptr(clas[0])
		_new = clas[4]
	Wend
	
	If Int(Byte Ptr(_new)) <> 0 Then
' Call constructor if one exists (if one doesn't, you should run very far in the opposite direction)
		_new(p)
	EndIf
	
	Return p
End Function

Public

Global SwapClass:Byte Ptr(obj:Object, newtype:TTypeID) = Byte Ptr(_SwapClass)
Global AllocateObject:Object(sz:Int, initType:TTypeID) = Byte Ptr(_AllocateObject)

Comments

None.

Code Archives Forum