Python/D API
Kirk McDonald
kirklin.mcdonald at gmail.com
Wed May 24 14:17:22 PDT 2006
I've managed to create a DLL that crashes horribly. Hooray!
There are numerous references in a Google search to Deja Augustine's
port of the Python/C API headers to D, but the site
(http://www.scratch-ware.net/dfiles/) is down, and apparently has been
for a while. Further searching revealed a mirror of some version of the
header at http://jcc_7.tripod.com/d/pythond/ .
The header (I quickly discovered) is for version 2.3 of Python, where
the current version is 2.4. It was also written for a two-year-old
version of D, though no changes on this front appear to be needed. The
differences in the Python API between the two versions are minimal
(http://docs.python.org/whatsnew/node14.html), so I'm working on the
assumption that this header will work with the 2.4 DLL with just a name
change.
Anyway, I've managed to get something that compiles and even imports
into a Python session without complaint, but as soon as I try to call a
function in it, the interpreter locks up and crashes.
The code I have is first based on the "Simple Example" in the Python
"Extending and Embedding" docs
(http://docs.python.org/ext/simpleExample.html), and also takes code
from the D guide to writing DLLs (http://digitalmars.com/d/dll.html).
So there are three source files involved, here: dll.d, taken directly
from the D guide to DLLs; python24.d, which is basically Deja's header
renamed with some minor modifications; and example.d, which reads thus:
[example.d]
import python24;
import std.c.stdio;
extern (C) PyObject *
ex_foo(PyObject *self, PyObject *args)
{
printf("Hello, world\n");
Py_INCREF(Py_None);
return Py_None;
}
PyMethodDef[] example_methods = [
{"foo", &ex_foo, 1, "foo() doc string"},
{ null, null, 0, null }
];
export extern (C)
void
initexample()
{
Py_InitModule("example", example_methods);
}
// EOF
I also have a python24.lib created with implib:
C:>implib /system python24.lib c:\windows\system32\python24.dll
Finally, I have an example.def:
[example.def]
LIBRARY "example.lib"
EXETYPE NT
SUBSYSTEM WINDOWS,5.0
CODE PRELOAD DISCARDABLE SHARED EXECUTE
DATA PRELOAD SINGLE WRITE
The DLL is compiled with:
C:>dmd -ofexample.dll dll.d example.d python24.d python24.lib example.def
The example.dll is generated. I then start a python session and do the
following:
>>> import sys
>>> # Add the location of example.dll to the Python path
>>> sys.path.append('C:\\Projects\\pyd_test')
>>> import example
>>> example.foo
<built-in function foo>
This is good so far as it goes, but actually calling foo:
>>> example.foo()
Hello, world
And then CRASH! Windows politely informs me that python.exe has
encountered a problem, and would I like to send an error report to
Microsoft?
The fact that "Hello, world" is actually printed out is encouraging.
However, I'm slightly stumped as to where to go next.
-Kirk McDonald
More information about the Digitalmars-d
mailing list