Python C 扩展级别的间接

问题描述

我正在尝试用 C 编写一个简单的 python 扩展。但是,当我尝试编译 setup.py 时,它不断抛出有关间接级别的这些错误。我是 C 的菜鸟,但在谷歌搜索错误一段时间后,我认为指针有问题。只是我不知道哪位指点!有人可以帮我吗。

这是 C:

#include <Python.h>

static PyObject *exmod_devide(PyObject *self,PyObject *args){
    double a,b;

    // parse the data
    if(!PyArg_ParseTuple(args,'dd',&a,&b)){  // this is line 7,which throws the first two errors.
        return NULL;
    }
    else{
        return PyFloat_FromDouble(a/b);
    }
}

static PyMethodDef module_functions[] = {
    { "devide",exmod_devide,METH_VaraRGS,"Method for deviding two values" },{ NULL,NULL,NULL }
};

PyMODINIT_FUNC init_exmod(void){
    return PyModule_Create(&module_functions);  // this is line 21,which throws the next two errors
}

为了更好的衡量,我包含了 setup.py

from distutils.core import Extension,setup

module1 = Extension('exmod',sources=['exmodmodule.c'])

setup(name='exmod',ext_modules=[module1,])

这是错误

exmodmodule.c(7): warning C4047: 'function': 'const char *' differs in levels of indirection from 'int'
exmodmodule.c(7): warning C4024: 'PyArg_ParseTuple': different types for formal and actual parameter 2
exmodmodule.c(21): warning C4047: 'function': 'PyModuleDef *' differs in levels of indirection from 'PyMethodDef (*)[2]'
exmodmodule.c(21): warning C4024: 'PyModule_Create2': different types for formal and actual parameter 1

解决方法

exmodmodule.c(7): 警告 C4024: 'PyArg_ParseTuple': 形参和实参 2 的不同类型

这告诉你你需要知道的一切。我们来看参数2:

PyArg_ParseTuple(args,'dd',&a,&b)

第二个参数是 'dd',您患了语言阅读障碍。在 C 中,与 Python 不同,字符串总是在双引号中。你想要

PyArg_ParseTuple(args,"dd",&b)

作为技术问题,'dd' 在 C 中是由 'd' 的 ASCII 值形成的整数常量。由于小写的 'd' 是 0x64,因此该整数自然是 0x6464。一些编译器有时会警告多字符整数常量,但它们仍然是语言的一部分。