Problem with Python Extensions

John Machin sjmachin at lexicon.net
Thu Mar 21 06:53:51 EST 2002


cmbardon at engmail.uwaterloo.ca (Chris Bardon) wrote in message news:<5c2b81.0203202321.50bf8908 at posting.google.com>...
> I'm trying to write a simple Python extension for use in Truespace
> 4.3.
> The problem is, my extension crashes truespace whenever I
> try to import it.  I've created the dll using MS Visual C++ 6 and
> Python 1.5-I've also included the source for the dll below (like I
> said-starting simple).  When I try to import this into truspace's
> python interface (import CommExt), the script causes an invalid page
> exception in MFC42.DLL.  I'm linking this against python15.lib, as
> obtained from python.org.

I presume that Truespace (which I had never heard of until now) is
constraining you to use Python 1.5.2. I also presume that you know
that you can't mix and match --- if the Truespace/Python side is say
2.0, then it will barf on your 1.5.x (you didn't say what x was; it
had better be 2).

"I'm linking this against" implies you are not using distutils. You
should be; it greatly simplifies making extensions. It is available
for Python 1.5.2 as a separate download.

> If anyone has had a similar problem, or can see from my source what my
> problem might be, your help would be greatly appreciated.
> 
> Thanks,
> 
> Chris Bardon
> 
> 
> //CommExt.cpp

Uh-ohh -- try it as C, not as C++

> //Another stab at making a truespace extension
> 
> #include "Python.h"
> 
> PyObject* comm(PyObject *self, PyObject *args);
> 

It's usual to put the PyMethodDef *after* all the functions; this
reduces the need for forward declarations.

> static PyMethodDef commMethods[] =
> {
>   {"comm", comm, 1},

This is unlikely to be the cause of your crash, but you should really
be using
METH_blah_blah instead of magic numbers like 1.

>   {NULL,      NULL}        /* Sentinel */
> 
> };
> 
> static PyObject *CommExtError;
> 
> extern "C"__declspec(dllexport) void initCommExt()

This doesn't even compile with Borland C version 5.5.

Try the standard spell from xxmodule.c:

DL_EXPORT(void) initCommExt()

If that doesn't work, try just

void InitCommExt()

> {
> 	Py_InitModule("CommExt", commMethods);  //this is the line that
> crashes TS!
> }

The comm() function should be declared as static...

> PyObject* comm(PyObject *self, PyObject *args)
> {
> 	int result=42;
> 	return Py_BuildValue("i", result);
> }

With the DL_EXPORT line (and no other changes), your code in commext.c
(not .cpp) and a suitable setup.py give the following with Python
1.5.2 and the Borland BCC 5.5 compiler:

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import CommExt
>>> CommExt.comm()
42
>>>

If you manage to get it that far with Python at the command line, then
try using it through Truespace.

HTH,
John



More information about the Python-list mailing list