我最近开始使用Python/C API使用C代码为Python构建模块。我一直试图将一个Python数字列表传递给一个C函数,但没有成功:
asdf U模块c
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <Python.h>
int _asdf(int low, int high, double *pr)
// ...
for (i = 0; i < range; i++)
{
printf("pr[%d] = %f\n", i, pr[i]);
}
// ...
return 0;
}
static PyObject*
asdf(PyObject* self, PyObject* args)
{
int low, high;
double *pr;
// maybe something about PyObject *pr ?
if (!PyArg_ParseTuple(args, "iiO", &low, &high, &pr))
return NULL;
// how to pass list pr to _asdf?
return Py_BuildValue("i", _asdf(low, high, pr));
}
static PyMethodDef AsdfMethods[] =
{
{"asdf", asdf, METH_VARARGS, "..."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initasdf(void)
{
(void) Py_InitModule("asdf", AsdfMethods);
}
使用setup.py构建模块:
from distutils.core import setup, Extension
module1 = Extension('asdf', sources = ['asdf_module.c'])
setup (name = 'asdf',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1])
使用test_module.py中的模块:
import asdf
print asdf.asdf(-2, 3, [0.7, 0.0, 0.1, 0.0, 0.0, 0.2])
但是,我得到的结果是:
pr[0]=0.000000
pr[1]=0.000000
pr[2]=0.000000
pr[3]=0.000000
pr[4]=0.000000
pr[5]=-南
此外,它如何返回一个
n
值数组(其中n
是一个固定数字),而不是返回0? 最佳答案
这个例子将向您展示如何
获取列表的长度
为double
的数组分配存储
获取列表中的每个元素
将每个元素转换为double
将每个转换后的元素存储在数组中
代码如下:
#include "Python.h"
int _asdf(double pr[], int length) {
for (int index = 0; index < length; index++)
printf("pr[%d] = %f\n", index, pr[index]);
return 0;
}
static PyObject *asdf(PyObject *self, PyObject *args)
{
PyObject *float_list;
int pr_length;
double *pr;
if (!PyArg_ParseTuple(args, "O", &float_list))
return NULL;
pr_length = PyObject_Length(float_list);
if (pr_length < 0)
return NULL;
pr = (double *) malloc(sizeof(double *) * pr_length);
if (pr == NULL)
return NULL;
for (int index = 0; index < pr_length; index++) {
PyObject *item;
item = PyList_GetItem(float_list, index);
if (!PyFloat_Check(item))
pr[index] = 0.0;
pr[index] = PyFloat_AsDouble(item);
}
return Py_BuildValue("i", _asdf(pr, pr_length));
}
注意:删除空白和大括号以防止代码滚动。
测试程序
import asdf
print asdf.asdf([0.7, 0.0, 0.1, 0.0, 0.0, 0.2])
输出
pr[0] = 0.700000
pr[1] = 0.000000
pr[2] = 0.100000
pr[3] = 0.000000
pr[4] = 0.000000
pr[5] = 0.200000
0
关于python - 使用Python/C API将Python列表传递给C函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55595835/