Wrapping Python - A function wrapping template

Kirk McDonald kirklin.mcdonald at gmail.com
Tue Jun 13 12:55:13 PDT 2006


In wrapping Python with D, I have just made a large step:

[testdll.d]
import python;
import pyd.pyd; // My "Python/D" package

int str_len(char[] str) {
     return str.length;
}

extern (C) {

PyMethodDef testdll_GlobalMethods[] = [
     { "str_len", cast(PyCFunction)&func_wrap!(str_len).func, 
METH_VARARGS, "" },
     { null, null, 0, null }
];

export void inittestdll() {
     _loadPythonSupport();

     PyObject* m = Py_InitModule("testdll", testdll_GlobalMethods);
}

} /* end extern (C) */
// EOF

(In a Python session:)
 >>> import testdll
 >>> testdll.str_len("This")
4

Note the "func_wrap" template. This takes a regular D function and wraps 
it with something that can be exposed to Python. There are some 
limitations, as yet: The arguments and return type of the function must 
be ones it knows how to convert to and from Python, and there is not yet 
a mechanism for adding types to this list. It also does not yet support 
default arguments. It would also be nice to wrap all of the business 
with the method definition array. This can all be done.

I'd like to acknowledge the work of David Rushby, whose "celerid" 
project and updated Python header were invaluable, as well as Deja 
Augustine, who first took a crack at the header.

Daniel Keep and Tom S also proivded some useful function 
property-deriving templates.

This library, as it exists now, is more a proof-of-concept than a useful 
library, so I'm not quite prepared to release it yet.

-Kirk McDonald



More information about the Digitalmars-d mailing list