making py modules with C

Roger Hansen rogerha at ifi.uio.no
Tue Mar 21 07:09:52 EST 2000


* Shaun Hogan
> > im tryin to make a module called mod so that when you type:
> > >>>from mod import *
> > >>> work()
> > in the python interpreter, it prints
> > >>>"worked"
> > but of course it isnt working for me, could you please tell me whats wrong
> > with the code:
> > it makes ok i get 2 errors :undefined referance to main and undefined
> > referance to PyInitModule4????.
> > i cp it to /opt/python/Python-1.5.2/Modules
> > i do a make in /opt/python/Python-1.5.2
> > in Setup.local i added "mod newmodule.o -ldl -lsocket"
> > and it still says the module mod does not exist????

> #include "Python.h"

I prefer #include <Python.h>

> #define DEBUG
>
> static PyObject * getsub(PyObject * self, PyObject * args);

Don't need this one actually.

> static PyMethodDef wahooMethods[]=
> {
>     {"work",getsub,METH_VARARGS},
>     {NULL.NULL}

Some typos her, look at code beneath. 

> } ;
>
> void initmod()
> {
>     (void) PyInitModule ("mod", wahooMethods);
> }
Some typos her, look at code beneath. 


>
> #ifdef NEEDMAIN
> int main (void)
> {
>     printf("worked\n");
> }
> #endif
>
> static PyObject * getsub(PyObject * self, PyObject * args);
> {
>     printf("worked\n");
> }
This one should return something.


This code work fine, at least on my Linux. I changed some names so the
module is more consistent andcleaned up a bit. 

/*newmodule.c*/
#include <Python.h>
#define DEBUG

static PyObject * mod_getsub(PyObject * self, PyObject * args)
{
    printf("worked\n");
    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef modMethods[] = {
    {"work", mod_getsub, METH_VARARGS},
    {NULL, NULL}
};

void initmod()
{
    (void) Py_InitModule ("mod", modMethods);
}

Compile:
:-) gcc -fpic -Wall -ansi -I$EXTSOFT/$MACHINE_TYPE/include/python1.5 -c newmodule.c 
:-) gcc -shared newmodule.o -o modmodule.so
:-) python
Python 1.5.2 (#1, Mar 13 2000, 10:42:14)  [GCC 2.95.2 19991024 (release)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> from mod import *
>>> work()
worked


HTH,

R



More information about the Python-list mailing list