Python C binding error

让人想犯罪 __ 提交于 2019-12-23 02:02:13

问题


I have written a Python API in C code and saved the file as foo.c.

Code:

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

static PyObject *foo_add(PyObject *self, PyObject *args)
{
    int a;
    int b;

    if (!PyArg_ParseTuple(args, "ii", &a, &b))
    {
        return NULL;
    }

    return Py_BuildValue("i", a + b);
}

static PyMethodDef foo_methods[] = {
    { "add", (PyCFunction)foo_add, METH_VARARGS, NULL },
    { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC initfoo()
{
    Py_InitModule3("foo", foo_methods, "My first extension module.");
}

When i try to compile using the below mentioned command i am getting compilation error.

Command: gcc -shared -I/usr/include/python2.7 foo.c -o foo.so

Error: gcc -shared -I/usr/include/python2.7 foo.c -o foo.so /usr/bin/ld: /tmp/ccd6XiZp.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC /tmp/ccd6XiZp.o: error adding symbols: Bad value collect2: error: ld returned 1 exit status

If i give compilation command with "-c" option, its getting compiled successfully and created the object file foo.so (This is the executable file).

I have to create a object file (without using -c option in compilation command) and import them in Python shell to verify it.

Please let me know what am i doing wrong here.

来源:https://stackoverflow.com/questions/28511138/python-c-binding-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!