Saturday, January 19, 2013

D dynamic runtime function calling

Recently I did some work towards making a dynamic function caller in D. Note this is a very unsafe operation in such a language.
The premise is simple take any argument and then call a function without a return type.

The answer didn't appear as simple though.
I manually pushed to the stack the arguments then called using a pointer which has been casted to void the function.
Great it works! But umm how do we push arguments to the stack? That is the hard part.
Primitives have to be dealt with individually. Structs have no super type and Objects aka classes have the Object super type so very easy. Arrays are also a type so they are easy to do when registering a type. Last associative arrays a type that requires two other types to make it; not so easy.

I got Objects, primitives, arrays and any other type you manually register. Why the registering? Because I used the Variant type and this is where it all falls apart.
The Variant type is great for storing and retrieving values out off, IF you know the type at compile time for when you retrieve it.
So using templates I created a registration system that created a function that was designed specifically for a type you register.

Most of the time it was a non issue with calling the get!type function on Variant and then just exiting the function created but some which types use a more complex pointer values in registers had to be modified to be allowed for.

Also the float type was stored in different registers different from other types its size. I implemented the registration system to allow for system level types and user types. The system types have the override for said type that was manually implemented.

How could this have been done simpler?
In short a container type that allowed for pushing the value directly on to the stack without knowing its type. Because the type and hence its size was known directly at creation I don't need to know it when pushing; it should have been retrieved and stored then (value.sizeof).
This would have void'd the need for the registration system completely.

To see this check out link.

I hope this gives you all some ideas; but remember this is not safe,even if I called it that. D is simply not the right type of language to do any sort of reflection type activity like this.

Concurrency design with D

During my development with CivBot (an IRC bot written in D) I have come across some things which make me go wow; One of these is threading.
This may seem like well just use mutexs but how can you really use it efficiently is what I am trying to come to grips with.
I'm looking at two types of concurrency in D, mutexs and message passing.