Exposing D functions to python¶
The heart of PyD’s function wrapping is the def template function.
import pyd.pyd;
import std.stdio;
void foo(int i) {
writefln("You entered %s", i);
}
void bar(int i) {
writefln("bar: i = %s", i);
}
void bar(string s) {
writefln("bar: s = %s", s);
}
void baz(int i=10, string s="moo") {
writefln("i = %s\ns = %s", i, s);
}
extern (C) void PydMain() {
// Plain old function
def!(foo)();
// Wraps the lexically first function under the given name
def!(bar, PyName!"bar1")();
// Wraps the function of the specified type
def!(bar, PyName!"bar2", void function(string))();
// Wraps the function with default arguments
def!(baz)();
module_init();
}
- Notes
- Any function whose return type and parameters types are convertible by
- All calls to def must occur before the call to module_init or py_init PyD’s type conversion can be wrapped by def.
- def can’t handle
out
,ref
, orlazy
parameters. - def can’t handle functions with c-style variadic arguments
- def can handle functions with default and typesafe variadic arguments
- def supports skipping default arguments (on the python side) and will automatically fill in any omitted default arguments
- def-wrapped functions can take keyword arguments in python
def-wrapped functions can be called in the following ways:
D function | Python call |
---|---|
void foo(int i); |
foo(1)
foo(i=1)
|
void foo(int i = 2, double d = 3.14); |
foo(1, 2.0)
foo(d=2.0)
foo()
|
void foo(int[] i...); |
foo(1)
foo(1,2,3)
foo([1,2,3])
foo(i=[1,2,3])
|
def template arguments¶
Aside from the required function alias, def recognizes a number of poor-man keyword arguments, as well as a type specifier for the function alias.
def!(func, void function(int), ModuleName!"mymodl")();
Order is not significant for these optional arguments.
PyName¶
Specify the name that python will bind the function to
Default: the name of the exposed function