Python C绑定错误 [英] Python C binding error
问题描述
我已经用C代码编写了Python API,并将文件另存为foo.c.
I have written a Python API in C code and saved the file as foo.c.
代码:
#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.
命令:gcc -shared -I/usr/include/python2.7 foo.c -o foo.so
Command: gcc -shared -I/usr/include/python2.7 foo.c -o foo.so
错误: gcc -shared -I/usr/include/python2.7 foo.c -o foo.so /usr/bin/ld:/tmp/ccd6XiZp.o:在创建共享库时,无法使用针对".rodata"的重定位R_X86_64_32;用-fPIC重新编译 /tmp/ccd6XiZp.o:添加符号时出错:值错误 collect2:错误:ld返回1退出状态
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
如果我使用"-c"选项给出编译命令,则编译命令将成功编译并创建目标文件foo.so(这是可执行文件).
If i give compilation command with "-c" option, its getting compiled successfully and created the object file foo.so (This is the executable file).
我必须创建一个目标文件(不使用编译命令中的-c选项)并将其导入Python Shell进行验证.
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.
推荐答案
在编译标志中,应包括-fPIC以编译为与位置无关的代码.这是动态链接库所必需的.
In your compilation flags you should include -fPIC to compile as position independent code. This is required for dynamically linked libraries.
例如
gcc -c -fPIC foo.c -o foo.o
gcc -shared foo.o -o foo
或一步一步
gcc -shared -fPIC foo.c -o foo.so
这篇关于Python C绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!