Jump to content
  • Advertisement
Sign in to follow this  
Mike.Popoloski

Unity Dynamic Dispatch in C#

This topic is 3744 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I was browsing the forums the other day when I ran across this thread, in which the OP wanted to use multiple dispatch in C#. Once it was discovered that this could not be done in C#, at least not directly, the topic flowed on to how his collision detection and handling might best be realized. It got me thinking though, on how multiple dispatch, or even dynamic dispatch, would work in C#. So when I got home I started coding, and this is what I came up with after a couple hours of work.
/// <summary>
/// Provides dynamic dispatch functionality for any given method.
/// </summary>
public class DynamicDispatcher
{
    // static data
    static Dictionary<Type, Dictionary<string, Dictionary<long, DynamicMethod>>> cachedDispatchers = 
        new Dictionary<Type, Dictionary<string, Dictionary<long, DynamicMethod>>>();

    // variables
    Dictionary<string, Dictionary<long, DynamicMethod>> storedMethods = new Dictionary<string, Dictionary<long, DynamicMethod>>();

    /// <summary>
    /// Gets the target.
    /// </summary>
    /// <value>The target.</value>
    public Object Target
    {
        get;
        private set;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DynamicDispatcher"/> class.
    /// </summary>
    /// <param name="target">The target object.</param>
    public DynamicDispatcher(object target)
    {
        // store the target
        Type type = target.GetType();
        Target = target;

        // if we haven't yet created data for this type, do so now
        if (!cachedDispatchers.ContainsKey(type))
            Generate(type);

        // grab a reference to the data
        storedMethods = cachedDispatchers[type];
    }

    /// <summary>
    /// Generates dynamic dispatch methods for a given type.
    /// </summary>
    /// <param name="type">The type.</param>
    /// <remarks>
    /// This method can be called to pre-generate the dynamic method bindings
    /// for a particular type. This will give a performance boost when creating
    /// a <see cref="DynamicDispatcher"/> for the first time.
    /// </remarks>
    public static void Generate(Type type)
    {
        // generate the data for the type
        Dictionary<string, Dictionary<long, DynamicMethod>> storedMethods = new Dictionary<string, Dictionary<long, DynamicMethod>>();

        // search for all methods marked with the Dynamic attribute
        foreach (MethodInfo method in type.GetMethods(BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy))
        {
            // grab the custom attributes
            DynamicAttribute[] attributes = (DynamicAttribute[])method.GetCustomAttributes(typeof(DynamicAttribute), true);
            if (attributes.Length != 1)
                continue;

            // figure out the name
            string name = string.IsNullOrEmpty(attributes[0].Name) ? method.Name : attributes[0].Name;

            // bind the method
            InternalBind(type, name, method);
        }

        // cache the new methods
        cachedDispatchers.Add(type, storedMethods);
    }

    /// <summary>
    /// Invokes the dynamic method with the specified name.
    /// </summary>
    /// <param name="name">The name of the method.</param>
    /// <param name="parameters">The parameters.</param>
    public void Invoke(string name, params object[] parameters)
    {
        // parameter checking
        if (string.IsNullOrEmpty(name))
            throw new ArgumentNullException("name");
        if (parameters == null || parameters.Length == 0)
            throw new ArgumentNullException("parameters");

        // invoke the method
        InternalInvoke(Target, name, parameters, typeof(void));
    }

    /// <summary>
    /// Invokes the dynamic method with the specified name.
    /// </summary>
    /// <param name="name">The name of the method.</param>
    public void Invoke(string name)
    {
        // parameter checking
        if (string.IsNullOrEmpty(name))
            throw new ArgumentNullException("name");

        // invoke the method
        InternalInvoke(Target, name, null, typeof(void));
    }

    /// <summary>
    /// Invokes the dynamic method with the specified name.
    /// </summary>
    /// <typeparam name="T">The return type of the method.</typeparam>
    /// <param name="name">The name of the method.</param>
    /// <param name="parameters">The parameters.</param>
    /// <returns>The return value of the method.</returns>
    public T Invoke<T>(string name, params object[] parameters)
    {
        // parameter checking
        if (string.IsNullOrEmpty(name))
            throw new ArgumentNullException("name");
        if (parameters == null || parameters.Length == 0)
            throw new ArgumentNullException("parameters");

        // invoke the method
        return (T)InternalInvoke(Target, name, parameters, typeof(T));
    }

    /// <summary>
    /// Invokes the dynamic method with the specified name.
    /// </summary>
    /// <typeparam name="T">The return type of the method.</typeparam>
    /// <param name="name">The name of the method.</param>
    /// <returns>The return value of the method.</returns>
    public T Invoke<T>(string name)
    {
        // parameter checking
        if (string.IsNullOrEmpty(name))
            throw new ArgumentNullException("name");

        // invoke the method
        return (T)InternalInvoke(Target, name, null, typeof(T));
    }

    /// <summary>
    /// Binds the specified method to the dispatcher's target type.
    /// </summary>
    /// <param name="name">The dynamic name of the method.</param>
    /// <param name="method">The method to bind.</param>
    public void Bind(string name, MethodInfo method)
    {
        // parameter checking
        if (string.IsNullOrEmpty(name))
            throw new ArgumentNullException("name");
        if (method == null)
            throw new ArgumentNullException("method");

        // call the internal method
        InternalBind(Target.GetType(), name, method);
    }

    /// <summary>
    /// Binds the specified method to the dispatcher's target type.
    /// </summary>
    /// <param name="method">The method to bind.</param>
    public void Bind(MethodInfo method)
    {
        // call the overload
        Bind(method.Name, method);
    }

    static void InternalBind(Type type, string name, MethodInfo method)
    {
        // grab the parameters
        ParameterInfo[] parameters = method.GetParameters();
        Type[] parameterTypes = new Type[parameters.Length];

        // calculate a hash for this method
        long hash = method.ReturnType.GetHashCode();
        for (int i = 0; i < parameters.Length; i++)
        {
            // store the parameter type as well so that we can use it later
            parameterTypes = parameters.ParameterType;
            hash += parameterTypes.GetHashCode();
        }

        // generate the dynamic method to wrap the target method
        DynamicMethod caller = new DynamicMethod(name, method.ReturnType, parameterTypes, type, true);
        ILGenerator generator = caller.GetILGenerator();
        generator.Emit(OpCodes.Ldarg_0);

        // generate op codes to load each argument onto the stack
        for (int i = 0; i < parameters.Length; i++)
            generator.Emit(OpCodes.Ldarg_S, i + 1);

        // finish up the method
        generator.Emit(OpCodes.Callvirt, method);
        generator.Emit(OpCodes.Ret);

        // add the method to the dictionary
        Dictionary<string, Dictionary<long, DynamicMethod>> storedMethods = cachedDispatchers[type];
        if (!storedMethods.ContainsKey(name))
            storedMethods.Add(name, new Dictionary<long, DynamicMethod>() { { hash, caller } });
        else
            storedMethods[name].Add(hash, caller);
    }

    object InternalInvoke(object target, string name, object[] parameters, Type returnType)
    {
        // ensure that we have this method
        if (!storedMethods.ContainsKey(name))
            throw new DynamicDispatchException("Dynamic method \"" + name + "\" not found at run time.");

        // calculate the hash
        long hash = returnType.GetHashCode();
        if (parameters != null)
        {
            // add each parameter to the hash
            foreach (object parameter in parameters)
                hash += parameter.GetType().GetHashCode();
        }

        // ensure that we have this particular method incarnation
        Dictionary<long, DynamicMethod> currentMethods = storedMethods[name];
        if (!currentMethods.ContainsKey(hash))
            throw new DynamicDispatchException("Could not locate desired overload for method \"" + name + "\"");

        // invoke the method
        return currentMethods[hash].Invoke(target, parameters);
    }
}

Once the dispatcher is generated for a particular type, calling methods on it is quite fast (only around 1.2 to 1.5 times slower than a straight method call). It handles multiple dispatch for any number of parameters, and indeed I believe even for differing return types. Here's an example of its usage:
interface IObject
{
}

class A : IObject
{
}

class B : IObject
{
}

class Handler
{
    [Dynamic]
    void HandleObjects(IObject obj1, IObject obj2)
    {
    }

    [Dynamic]
    void HandleObjects(A obj1, B obj2)
    {
    }
}

IObject obj1 = new A();
IObject obj2 = new B();
Handler handler = new Handler();

// demonstrating normal method
DynamicDispatcher dispatcher = new DynamicDispatcher(handler);
dispatcher.Invoke("HandleObjects", obj1, obj2);

// demonstrating extension method
handler.Invoke("HandleObjects", obj1, obj2);

You can also do some fairly wacky things, such as binding outside methods to a class and then calling them as if they were normal members of that class. They can even access private members of the class!
class MyClass
{
    private int data = 1;

    void Print()
    {
        Console.WriteLine(data);
    }
}

class SomeOtherClass
{
    // necessary for compile, but won't actually get used at runtime
    int data;

    void DoFoo()
    {
        data = 5;
    }
}

MyClass mc = new MyClass();
mc.Print();

mc.Bind("DoFoo", typeof(SomeOtherClass).GetMethod("DoFoo"));
mc.Invoke("DoFoo");
mc.Print();

That should print 1 and then 5, although right now I haven't tested this bit of functionality. So, does anyone see this as being actually useful? It was fun to implement, but I'm not sure it's worth using. Are there any cool things you could do with dynamic dispatch that I haven't thought about? See an opportunity for improvement? Have I screwed up my implementation royally? I want feedback.

Share this post


Link to post
Share on other sites
Advertisement
The toy language I'm working on based of off C# and supporting .NET types supports this sort of dispatching for specifically this sort of problem. That and similar problems surrounding 'items' and general component based game entities.

At a glance, you run into problems where the parameters are not the exact type as the method requires. And the IL compiler (iirc) requires special permissions to use, restricting the code somewhat. And there's the usual problems with strings rather than proper identifiers.


But all in all looks pretty complete, pretty well thought out and pretty snazzy.

Share this post


Link to post
Share on other sites
Hi,

I'm currently working on a multiple dispatch solution myself. I'm only interested in double dispatching and triple dispatching right now, ie.
double dispatching: invoke a method depending on the callee and the first (and only) argument
triple dispatching: invoke a method depending on the callee, and the first and second argument

Just to be sure we're talking about the same thing, here are example of double and triple dispatching:

Example for a double dispatching scenario: a strategy to walk a scene graph. Assume I have an interface "ISceneGraphWalker", a bunch of graph node types and several implementations of ISceneGraphWalker, like FrustrumCuller or so. In this case I want to do this:

void Traverse(Node node, ISceneGraphWalker){
Node node = graph.Root;
// calls ISceneGraphWalker.Process(Node node)
// but should map to Process(EntityNode), Process(LightNode) etc.
walker.Process(node);
foreach(Node child in node.Children){
Traverse(child, walker);
}
}

ISceneGraphWalker walker = new FrustrumCuller();
Traverse(graph.Node, walker);
...






Example for a triple dispatching scenario: collision detection.

ICollisionDetector d = new DefaultCollisionDetector();
IShape shapes = new IShape[]{new Rectangle(), new Circle(), new Line()};

for(int x = 0; x < shapes.Length; ++x){
for(int y = 0; y < shapes.Length; ++y){
// calls ICollisionDetector.Collide(IShape a, IShape b)
// but should map to Collide(Circle, Rectangle), Collide(Circle, Line) etc.
d.Collide(shapes[x], shapes[y]);
}
}






The solution I came up with is quite flexible and easy to use. I had a bunch of requirements to fulfil:
- no classic visitor pattern, as it does not work well as soon as the class hierarchy is extended
- no reflection
- no runtime code generation (not a real requirement, but preferable)
- no dictionary look up or similar
- no switch mess etc.
- reusable if possible (i.e. be able to put large parts of the system into a base class library and have the client do as little work as possible)

Enough talking, here's the code that the client would need to write to use triple dispatching:

// first, some client types

// base interface for shapes
// ITripleDispatchArg1 and ITripleDispatchArg2 are necessary
// to make the shape be usable in triple dispatching
public interface IShape : ITripleDispatchArg1, ITripleDispatchArg2 {
}

// deriving from TripleDispatchArg is not required, but convenient
// both ITripleDispatchArg1 and ITripleDispatchArg2 have only one method
// that can be implemented with one line of code
public class Circle : TripleDispatchArg<Circle>, IShape{}
public class Line : TripleDispatchArg<Line>, IShape{}
public class Rectangle : TripleDispatchArg<Rectangle>, IShape {}

// the class that handles collision detection
// deriving from TripleDispatchSink again is for convenience only
public class CollisionDetector : TripleDispatchSink<CollisionDetector> {
static CollisionDetector() {
#region Setup triple dispatch actions
// the type arguments define two of the three
// dimensions of triple dispatching (the last one is defined by the virtual
// methods in this class)
RegisterAction<Circle, Circle>((c, a, b) => c.Collide(a, b));
RegisterAction<Circle, Rectangle>((c, a, b) => c.Collide(a, b));
RegisterAction<Circle, Line>((c, a, b) => c.Collide(a, b));

RegisterAction<Rectangle, Circle>((c, a, b) => c.Collide(a, b));
RegisterAction<Rectangle, Rectangle>((c, a, b) => c.Collide(a, b));
RegisterAction<Rectangle, Line>((c, a, b) => c.Collide(a, b));

RegisterAction<Line, Circle>((c, a, b) => c.Collide(a, b));
RegisterAction<Line, Rectangle>((c, a, b) => c.Collide(a, b));
RegisterAction<Line, Line>((c, a, b) => c.Collide(a, b));
#endregion
}

// implementations of all registered combinations
protected virtual void Collide(Circle a1, Circle a2) {
Console.WriteLine("{0} <-> {1}", a1.GetType().Name, a2.GetType().Name);
}

protected virtual void Collide(Circle a1, Rectangle a2) {
Console.WriteLine("{0} <-> {1}", a1.GetType().Name, a2.GetType().Name);
}

protected virtual void Collide(Circle a1, Line a2) {
Console.WriteLine("{0} <-> {1}", a1.GetType().Name, a2.GetType().Name);
}

protected virtual void Collide(Rectangle a1, Circle a2) {
Console.WriteLine("{0} <-> {1}", a1.GetType().Name, a2.GetType().Name);
}

// etc.
}

// and finally, how to use the classes:
var collider = new CollisionDetector();
var shapes = new IShape[] {new Rectangle(), new Circle(), new Line()};
for (var x = 0; x < shapes.Length; ++x) {
for (var y = 0; y < shapes.Length; ++y) {
// dispatch is defines as
// ITripleDispatchSink.Dispatch(ITripleDispatchArg1 arg1, TripleDispatchArg2 arg2)
collider.Dispatch(shapes[x], shapes[y]);
}
}

// this will print:
Rectangle <-> Rectangle
Rectangle <-> Circle
Rectangle <-> Line
Circle <-> Rectangle
Circle <-> Circle
Circle <-> Line
Line <-> Rectangle
Line <-> Circle
Line <-> Line






I will write on the implementation details in my blog soon, but here's the basic idea:


// basic interfaces:
public interface ITripleDispatchSink {
void Dispatch(ITripleDispatchArg1 arg1, ITripleDispatchArg2 arg2);
}

public interface ITripleDispatchArg1 {
void Forward<TSink>(TSink sink, ITripleDispatchArg2 arg2);
}

public interface ITripleDispatchArg2 {
void Forward<TSink, TArg1>(TSink sink, TArg1 arg1) where TArg1 : ITripleDispatchArg1;
}


// ITripleDispatchSink should be implemented as:
class SomeDispatchSink : ITripleDispatchSink {
public void Dispatch(ITripleDispatchArg1 arg1, ITripleDispatchArg2 arg2){
arg1.Forward(this, arg2);
}
}

// ITripleDispatchArg1 should be implemented as
class SomeDispatchArg1 : ITripleDispatchArg1 {
public void Forward<TSink>(TSink sink, ITripleDispatchArg2 arg2){
arg2.Forward(sink, this);
}
}

// ITripleDispatchArg2 should be implemented as
class SomeDispatchArg2 : ITripleDispatchArg2 {
public void Forward<TSink, TArg1>(TSink sink, TArg1 arg1){
ActionRegistry<TSink, TArg1, SomeDispatchArg2>.Invoke(sink, arg1, this);
}
}

// ActionRegistry looks something like:
class ActionRegistry<T1,T2,T3>{
public Action<T1, T2, T3> Action;
public void Invoke(T1 t1, T2 t2, T3 t3){
Action(t1, t2, t3);
}
}

// so all you need to do is register the actions properly:
ActionRegistry<CollisionDetector, Circle, Circle>.Action = ...
ActionRegistry<CollisionDetector, Circle, Rectangle>.Action = ...
// ect.
// this is what "RegisterAction" does under the hood.






I hope it's more or less clear what is happening: the first three virtual method calls resolve the type of the three arguments (sink, arg1 and arg2). At the end we have a call to a generic method with three type arguments. This call is mapped to a non-generic method of a generic class with the same type arguments (ActionRegistry). The ActionRegistry holds a type safe delegate for each combination of classes which is finally invoked. I have a double dispatching solution which is similar, yet simpler. Adding more levels is technically possible but will introduce more and more types. I haven't found much use for more than triple dispatching, though.

This technique has some nice advantages:
- comparatively small overhead (a handful virtual calls)
- dispatch time is always O(1) irrespective of the number of e.g. shape classes
- very little code for the client to write

It has some disadvantages, of course:
- if there's not much code to be executed, the handful of virtual calls might be a comparatively greater overhead
- works only for types that implement the required interfaces (won't work for legacy code)
- "handwiring" the actions is not the nicest thing in the world.

Feedback is welcome.

Regards,
Andre

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!