python - 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
解决方案
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。一些编译器有时会警告多字符整数常量,但它们仍然是语言的一部分。
推荐阅读
- ios - 无法使用源 URL 中的 alamofire 上传多个文件-swift
- machine-learning - 坚持理解 TD(0) 和 TD(λ) 的更新用途之间的区别
- ruby-on-rails - 如何为非主分支设置heroku作为测试,然后将其合并到主分支中?
- javascript - 在同一选项卡中检测 localStorage 的变化
- c - 在这个 GTK 应用程序中如何创建一个窗口?
- asp.net-core - nopCommerce asp.net 核心性能
- javascript - 谷歌日历与完整日历 io 同步
- sockets - Lisp 中的套接字
- java - 子组上的 Java 正则表达式
- scala - 如何从 Scalaz 中的 Future 中获取价值?