使用python/c扩展接收错误答案

2024-09-29 00:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python的c扩展制作一个简单的模块。我只想加两个双值。但得到错误的结果值。我找不到错误。我的文件:

附件c

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

附加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;
}

你知道吗设置.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 谢谢你的帮助。你知道吗


Tags: thebuildaddreturnincludevaluelinuxstatic
1条回答
网友
1楼 · 发布于 2024-09-29 00:11:41

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

相关问题 更多 >