1. ariovistus
  2. pyd


ariovistus  committed 9f3a479

Edited online

  • Participants
  • Parent commits f5ef25f
  • Branches default

Comments (0)

Files changed (1)

File FuncWrap.wiki

View file
+==Function wrapping==
+Exposing D functions to Python is easy! The heart of Pyd's function wrapping features is the def template function:
+void def(alias fn, char[] name = symbolnameof!(fn), fn_t = typeof(&fn), uint MIN_ARGS = minArgs!(fn)) (char[] docstring="");
+* **fn** is the function to wrap. Note that this is an alias parameter. def is only capable of wrapping full-fledged functions, not function pointers, function literals, or delegates.
+* **name** is the name the function will have inside of Python. Usually, you don't have to specify this. (Special thanks to Don Clugston's Nameof module.)
+* **fn_t** is the function type of the function. Typically, you won't have to specify this. It is used to wrap overloaded functions. (See below.)
+* **MIN_ARGS** is the minimum number of arguments this function can accept. It is used when a function has default arguments. The minArgs template can derive the correct number automatically, so you typically won't specify this manually.
+    docstring is the function's docstring. Note that this is a regular function argument!
+All calls to def must occur before calling module_init. Any function whose return type and arguments are convertible can be wrapped by def. def can only wrap functions with in arguments (not out or ref or lazy). def also provides support for wrapping overloaded functions as well as functions with default arguments. Here are some examples:
+import pyd.pyd;
+import std.stdio;
+void foo(int i) {
+    writefln("You entered ", i);
+void bar(int i) {
+    writefln("bar: i = ", i);
+void bar(char[] s) {
+    writefln("bar: s = ", s);
+void baz(int i=10, char[] 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, "bar1");
+    // Wraps the function of the specified type
+    def!(bar, "bar2", void function(char[]));
+    // Wraps the function with default arguments
+    def!(baz);
+    module_init();
+And when used in Python:
+>>> import testmodule
+>>> testmodule.foo(10)
+You entered 10
+>>> testmodule.bar1(20)
+bar: i = 20
+>>> testmodule.bar2("monkey")
+bar: s = monkey
+>>> testmodule.baz()
+i = 10
+s = moo
+>>> testmodule.baz(3)
+i = 3
+s = moo
+>>> testmodule.baz(4, "apple")
+i = 4
+s = apple