python - 为什么基于 C 的 Python 扩展总是返回相同的值?
问题描述
下面的代码看起来非常简单。一个整数被传递给 Python 中的函数,该函数在 C 中创建一个 PyList,然后填充它:
你好.c:
#include <Python.h>
PyObject* getlist(int *len)
{
printf("Passed to C: %d\n", *len);
PyObject *dlist = PyList_New(*len);
double num = 0.1;
for (int i = 0; i < *len; i++)
{
PyList_SetItem(dlist, i, PyFloat_FromDouble(num));
num += 0.1;
}
return dlist;
}
static char helloworld_docs[] =
"Fill docs where possible\n";
static PyMethodDef helloworld_funcs[] = {
{"getlist", (PyCFunction)getlist, METH_VARARGS, helloworld_docs},
{NULL}
};
static struct PyModuleDef Helloworld =
{
PyModuleDef_HEAD_INIT,
"Helloworld", // module name
"NULL", // module documentation
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
helloworld_funcs
};
PyMODINIT_FUNC PyInit_helloworld(void)
{
return PyModule_Create(&Helloworld);
}
设置.py:
from distutils.core import setup
from distutils.extension import Extension
setup(name='helloworld',
version='1.0',
ext_modules=[Extension('helloworld', ['hello.c'])])
使用pkg.py:
#!/usr/bin/python
import sys
import helloworld
print("Input to Python:", sys.argv[1])
print (helloworld.getlist(sys.argv[1]))
我构建和安装使用
python3 setup.py build
python3 setup.py install
我没有看到任何错误。
当我测试它时会发生奇怪的行为。例如:
python3 usepkg.py 4
无论我作为参数给出什么值,输出总是相同的:
Input to Python: 4
Passed to C: 6
[0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6]
传递给 C 的值始终为 6。无论输入参数是 int 还是 Py_ssize_t,这都是相同的。我错过了什么?
解决方案
我很惊讶在构建时这里没有警告,函数的类型不应该是它们的原始类型,而是PyObject*
- 然后你将解析类型并执行你的函数
这是对您的功能的调整:
PyObject* getlist(PyObject* self, PyObject* args)
{
int len;
if (!PyArg_ParseTuple(args, "i", &len)) {
return NULL;
}
printf("Passed to C: %d\n", len);
PyObject *dlist = PyList_New(len);
double num = 0.1;
for (int i = 0; i < len; i++)
{
PyList_SetItem(dlist, i, PyFloat_FromDouble(num));
num += 0.1;
}
return dlist;
}
有关这方面的更多信息,请参阅解析参数和构建值文档
您得到的数字可能是PyObject*->ob_refcount
(self
对 C 模块的引用数)中的值
就我而言,我看到的是 4 而不是 6,尽管我可能使用不同版本的 python 和/或调用方法
推荐阅读
- swift - 如何解决链接器命令在 Xcode 10 中因退出代码 1 失败(使用 -v 查看调用)而失败
- android - Android AOSP 升级
- python-2.7 - 每 n 秒更改一个变量
- r - 你如何删除R中的异常值?
- python - 如何判断一个部分是否满足所有参数
- mysql - MySQL TIMESTAMP 是存储为 Unix 时间还是 ISO 8601?
- json - 使用命令行工具删除结尾的 json 逗号
- database - 在数据库中加密和解密密码
- r - 如何拆分数据框的列并重塑它?
- php - 使用 AES_ENCODE 解码存储在 MySQL 中的 php 数据