advanced function binding

Kirk McDonald kirklin.mcdonald at gmail.com
Wed Mar 28 01:45:03 PDT 2007


Moritz Warning wrote:
> Hi,
> 
> I try to write a RPC interface in D and have problems
> to start. I've already written the code in C++, but it became
> quite unmanageable and ugly because I
> had to write various workarounds.
> 
> The core problem is to hide an arbitrary (member) function pointer
> in a class. The argument values are provided _later_ in
> the form of a char[][] to a class function:
> void setArgs(char[][] args)
> 
> The wrapped function is called later by a class function that should rely on two template parameters only; the type of object the function will be called on, and the return type:
> R call(R,T)(T obj) { /**/ }
> For the type conversion I have several global T convert(T)(char[]) functions.
> 
> I've read about std.bind and recursive templates but wasn't able to
> make much use of them.
> I have thought about to pass a lazy template delegate (with convert(T)(char[]) inside)
> to std.bind, but that's apparently not possible
> 
> Maybe somebody can give me a push into the right direction. :-)
> .

This problem is highly analogous to how Pyd exposes D functions to 
Python. (Only instead of doing a char[] -> T conversion, Pyd does a 
PyObject* -> T conversion.)

There are two issues involved here:

First, the class is storing a pointer to a member function, a concept 
which D does not directly support. Instead, D has the generally more 
useful concept of delegates, which is a fat pointer combining the 
pointer to the member function and an object reference into a single 
package. While this is usually more useful, it can get in the way of 
writing a dispatch mechanism like you seem to want (and which Pyd uses 
to implement class wrapping). Luckily, you can access the internals of a 
delegate directly to get around this:

class Foo {
     void foo() {}
}

{
     void delegate() dg;
     dg.funcptr = &Foo.foo;
     dg.ptr = new Foo;
     dg();
}

Second is actually calling the function with the provided arguments. To 
explain how Pyd does it, I shall dust off this ancient pastebin, from 
when tuples were first added to the language:

http://paste.dprogramming.com/dpbaqugv.php

That paste is a rough outline of how Pyd's function wrapping works, and 
I think it is exactly what you are looking for.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list