2

I'm trying to extend Python with C. My C code compiles and I get a .so file, but then on import to Python, I get this error:

ImportError: dlopen(/Users/.../python/PYC/isprime.so, 2): no suitable image found.  Did find:
    /Users/.../python/PYC/isprime.so: can't map

Here is my C code:

#include <Python.h>
#include <stdio.h>


static PyObject *is_prime(PyObject *self, PyObject *args)
{
    int i;
    int num;
    int primes[] = {};
    PyArg_ParseTuple(args, "b b", &num, &primes);
    int max = num/2;

    if(num % 2 == 0) {
        return 0;
    } else {
        for(i=0; primes[i] <= max; i++) {
            if(num % primes[i] == 0) {
                return Py_BuildValue("i", 0);
            }
        }
        return Py_BuildValue("i", 1);
    }
}

static PyMethodDef is_primeMethods[] = {
    /* name, function, argument type, docstring */ 
    {"is_prime", is_prime, METH_VARARGS, "Detect primes"}, 
    /* An end-of-listing sentinel: */ 
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC 
init_isprime(void) 
{ 
    PyObject *m;
    m = Py_InitModule("is_prime", is_primeMethods);
}

int main(int argc, char *argv[])
{
    Py_SetProgramName(argv[0]);

    Py_Initialize();

    init_isprime();
}

And my makefile:

PYLIB = /usr/bin 
PYINC = /usr/include/python2.5

isprime.so: isprime.c
    gcc isprime.c -g -I$(PYINC) -shared -L$(PYLIB) -m64 -lpython2.5 -o isprime.so

clean:
    rm -f isprime.so

I've searched everywhere for this "can't map" error, but couldn't find anything. Im running osx 10.6.8. Can anybody shed some light? Also, are all these boilerplate functions also necessary to make it work? Thanks in advance!

  • 1
    Might be easier to try using setuptools or distribute to build your module as its likely the signature for your SO isn't what the python executable was expecting. – David Apr 23 '13 at 21:15
  • This for Python 2.7.4 but ideally with some research should be usable at Py2.5 as well - http://docs.python.org/2/extending/building.html – David Apr 23 '13 at 21:19

0 Answers0