首页 > 解决方案 > 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, 0, 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

标签: pythoncpointersc-api

解决方案


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

这告诉你所有你需要知道的。让我们看一下参数2:

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

第二个参数是'dd',你感染了语言阅读障碍烦躁不安。在 C 中,与 Python 不同,字符串总是用双引号引起来。你要

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

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


推荐阅读