Pyd

Kirk McDonald kirklin.mcdonald at gmail.com
Wed Jul 5 14:21:38 PDT 2006


I've just added some nifty things to Pyd:

[testdll.d]
module testdll;

import python;
import pyd.pyd;
import std.stdio;

// d_type testing
void foo() {
     writefln("Boo!");
}

void foo(int i) {
     writefln("You entered %s", i);
}

void baz(int i=10, char[] s="moo") {
     writefln("i = %s\ns = %s", i, s);
}

class Foo {
     int m_i;
     this() { }
     this(int i) { m_i = i; }
     this(int i, int j) { m_i = i + j; }
     void foo() {
         writefln("Foo.foo(): i = %s", m_i);
     }
     Foo opAdd(Foo f) { return new Foo(m_i + f.m_i); }
     int i() { return m_i; }
     void i(int j) { m_i = j; }
}

void delegate() func_test(Foo f) {
     return &f.foo;
}

extern (C)
export void inittestdll() {
     module_init("testdll");

     def!("foo", foo);
     // Python does not support function overloading. This allows
     // us to wrap an overloading function under a different name.
     def!("foo2", foo, 1, void function(int));
     // Default argument support is now automatic.
     def!("baz", baz);
     // Functions and delegates can be returned into Python. (Stay
     // tuned for the reverse operation of converting a Python
     // callable into a function/delegate.)
     def!("func_test", func_test);

     wrapped_class!("Foo", Foo) f;
     // opAdd is wrapped automatically
     f.init!(ctor!(int), ctor!(int, int));
     f.def!("foo", Foo.foo);
     f.prop!("i", Foo.i);
     finalize_class(f);
}
// EOF

In Python:

 >>> import testdll
 >>> f = testdll.Foo(20)
 >>> g = testdll.Foo(30)
 >>> h = f + g
 >>> h.i
50
 >>> a = testdll.func_test(f)
 >>> a()
Foo.foo(): i = 20
 >>> testdll.baz()
i = 10
s = moo

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://dsource.org/projects/pyd/wiki



More information about the Digitalmars-d mailing list