Wiki

Clone wiki

pyd / TypeConversion2

Advanced Type Conversion

It is frequently useful to extend Pyd's type conversion mechanisms. The usual way to do this is to wrap classes or structs. Pyd has two additional mechanisms for more complex situations.

void ex_d_to_python(dg_t) (dg_t dg);

This allows the user to define a function for returning a D type to Python. The dg may be either a function pointer or a delegate. The argument to the function pointer is of the type to convert. The return type of the function pointer can be any convertible type.

void ex_python_to_d(dg_t) (dg_t dg);

This allows the user to define a function for converting a Python object to a D type. The dg may be either a function pointer or a delegate. The argument to the function pointer can be any convertible type. The return type of the function pointer is the type to convert.

Conversion functions defined with either of the above functions only take effect if Pyd's regular type conversion mechanisms fail. This would usually happen if a wrapped function returns or has a parameter of some un-wrapped class or struct type.

Examples

import std.stdio;

struct S {
    int i;
}

S foo() {
    S s;
    s.i = 12;
}
void bar(S s) {
    writefln(s);
}

extern (C) void PydMain() {
    ex_d_to_python(delegate int(S s) { return s.i; });
    ex_python_to_d(delegate S(int i) { S s; s.i = i; return s; });

    def!(foo);
    def!(bar);
    module_init();
}

And in Python:

>>> foo()
12
>>> bar(20)
20

Updated