Extending Python with C API

Thierry Masson massonmousson at gmail.com
Fri Sep 14 03:05:15 CEST 2007


Hello,

I'm trying to use the C API to extend Python. I've looked at various books
and web sites (including the docs at python.org) and I can't get any of the
samples to work. Below is a very minimalist example that I'm trying to get
working and I was wondering if someone could tell me where I'm going wrong.
It's probably something very obvious to those familiar with this technique.

gtestmodule.c:
--------------------
#include "Python.h"

int GetInt(int iVal)
{
    return iVal;
}

char* GetString(void)
{
    return "This is the message";
}

PyObject* gtestmodule_GetInt(PyObject* pSelf, PyObject* pArgs)
{
    int x = 0;
    if (!PyArg_ParseTuple(pArgs, "i", &x))
        return NULL;
    GetInt(x);
    return PyBuildValue("i", x);
}

PyObject* gtestmodule_GetString(PyObject* pSelf, PyObject* pArgs)
{
    char* szMsg = GetString();
    return PyBuildValue("s", szMsg);
}

static PyMethodDef gtestmoduleMethods[] =
{
    {"GetInt", gtestmodule_GetInt, METH_VARARGS, "Description goes here"},
    {"GetString", gtestmodule_GetString, METH_VARARGS, "Description goes
here"},
    {NULL, NULL}
};

setup.py:
------------
from distutils.core import setup, Extension
setup(name = "gtestmodule",
      version = "1.0",
      maintainer = "thierry masson",
      maintainer_email = "blah at blah.com",
      description = "test module",
      ext_modules = [Extension("gtestmodule",["gtestmodule.c"])],
     )

test.py:
----------
import gtestmodule
print gtestmodule.GetInt(36);
print gtestmodule.GetString();

The setup script builds the library OK, and I've verified that
gtestmodule.so is getting created. But when I try to run a test script (
test.py, above) that uses the library, I get this error:

Traceback (most recent call last):
  File "test.py", line 2, in ?
    import gtestmodule
ImportError: ./gtestmodule.so: undefined symbol: PyBuildValue

The OS is Red Hat Enterprise Linux ES release 3 (Taroon Update 8), and the
Python version is 2.2.3 (rather old, I know, but I don't control the server
environment and my sysadmin tells me this is the most recent version of
Python officially supported by Red Hat.

Can anyone see where I'm going wrong?

Thanks!

Thierry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070913/9d95e802/attachment.html>


More information about the Python-list mailing list