使用python / c扩展名收到错误的答案

时间:2013-12-30 10:23:38

标签: python c python-c-api

我想为python制作带c扩展名的简易模块。我想只添加两个double值。但收到错误的结果值。我找不到错误。我的档案:

add.c

#include "add.h"
double add(double a, double b){
    return a+b;
}

add.h

double add(double a, double b);

_add.c

#include <Python.h>
static char module_docstring[] =
    "This module provides an interface for calculating two integers using C.";
static char add_docstring[] =
    "Calculate the two int of some data given a model.";
static PyObject *add_add(PyObject *self, PyObject *args);

static PyMethodDef module_methods[] = {
    {"add", add_add, METH_VARARGS, add_docstring},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC init_add(void)
{
    PyObject *m = Py_InitModule3("_add", module_methods, module_docstring);
    if (m == NULL)
        return;
}

static PyObject *add_add(PyObject *self, PyObject *args)
 {
     double a, b;
     /* Parse the input tuple */
     if (!PyArg_ParseTuple(args, "dd", &a, &b))
         return NULL;
     /* Call the external C function to compute the chi-squared. */
     double value = add(a, b);
     if (value < 0.0) {
         PyErr_SetString(PyExc_RuntimeError,
                     "Chi-squared returned an impossible value.");
         return NULL;
     }
     /* Build the output tuple */
     PyObject *res = Py_BuildValue("d", value);
     return res;
}

setup.py

from distutils.core import setup, Extension
setup(
    ext_modules=[Extension("_add", ["_add.c", "add.c"])]
)

我构建模块:

$ python setup.py build_ext --inplace

running build_ext building '_add' extension i686-linux-gnu-gcc
-pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c _add.c -o build/temp.linux-i686-2.7/_add.o
_add.c: In function ‘add_add’:
_add.c:30:6: warning: implicit declaration of function ‘add’ [-Wimplicit-function-declaration] i686-linux-gnu-gcc -pthread
-fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c add.c -o build/temp.linux-i686-2.7/add.o i686-linux-gnu-gcc -pthread -shared
-Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-i686-2.7/_add.o build/temp.linux-i686-2.7/add.o -o /home/nikolay/Documents/4COURSE-1/UNIX/lab3/cmodule/_add.so

在我用python编写之后:

 import _add
 print (_add.add(2.4, 3.5))

我收到: 1.0 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

关于隐式implicit declaration of function ‘add’的警告是错误的:在编译源文件时,它认为应该以与定义函数不同的方式调用函数。如果您在add.h中也包含_add.c文件,它应该可以正常工作(在我的计算机上也是如此)。