Quick Introduction

This tutorial covers ideas behind casting pointers, and what data is cast. I don't know the technical workings in the compiler, but I do know this works, and it's convenient if you are working with lots of information, that has a base-type of some sorts that it builds off of. Hopefully, this will make more sense as we go on.

Base-type

This is my wording for what Cpp would call Class x extends basetype
FreeBASIC, however, does not use Classes (yet), and definitely does not support "extends" in this context. I don't know if you would call this a hack, but it works, and I'm happy with it.

Code

You'll need to be familiar with cptr() and what pointers are.

So, you have your base type. For this, I'll use some code I'm using in a game, where I need all objects to share certain information for collision detection:

type ObjectDefinition
Collision Data
as integer typeID, objID
as ubyte integrity
Object Constants (for physics)
as single mass, size, e, u
end type

Any object will need this information, from a player's instance to any segment of floor.

Now, whatever data you put in this type, you'll want a quick way of defining and getting that information out.

This is how I'd do that:

#macro Object( typename )
type typename
object as ObjectDefinition
#endmacro

#macro endObject
end type
#endmacro

So, to make an object:
Object( test )
/' Fill in the data here '/
endObject

Now, to get the ObjectDefinition, you could do:
dim x as test
x.object

But, this makes it so you only have the object, so the x variable is no longer accessible.

Here is a better, more preferred approach:
dim x as test
var n = cptr( ObjectDefinition ptr, @x )
no, "n" can be recast to get the original x variable:
var revert = cptr( test ptr, n )
now, revert will point to x

The reason this works, is because in the macro, object is first, so it is the first bit of data found when casting.

Hope you enjoy,
-Oz
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki



sf.net phatcode