我试图理解Python C-Api是如何工作的,我想在Python和C Extension之间交换numpy数组.
所以,我开始了这个教程:http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html
试图在那里做第一个例子,计算2d numpy数组的跟踪的C模块对我来说非常整洁,因为我也想在2d数组中进行基本操作.
#include <Python.h>
#include "Numeric/arrayobject.h"
#include<stdio.h>
int main(){
Py_Initialize();
import_array();
}
static char doc[] =
"This is the C extension for xor_masking routine";
static PyObject *
trace(PyObject *self, PyObject *args)
{
PyObject *input;
PyArrayObject *array;
double sum;
int i, n;
if (!PyArg_ParseTuple(args, "O", &input))
return NULL;
array = (PyArrayObject *)
PyArray_ContiguousFromObject(input, PyArray_DOUBLE, 2, 2);
if (array == NULL)
return NULL;
n = array->dimensions[0];
if (n > array->dimensions[1])
n = array->dimensions[1];
sum = …Run Code Online (Sandbox Code Playgroud) 我想在C扩展中使用我的Numpy数组.在这种情况下,许多示例使用PyArrayObject的结构,
array->data , array->strides[0] , array->strides[1] , ...
如果我想以更熟悉(或更整洁)的方式到达我的数组,以及像
array[i][j]
我该怎么办呢?我应该使用类型转换(bool*)array-> data并使用我创建的C数组吗?(我的元素是bools)
我现在的功能声明是(当然没有完成)
static PyObject *
xor_masking(PyObject *self, PyObject *args)
{
PyObject *input;
PyObject *mask;
PyObject *adjacency;
PyObject *state;
PyArrayObject *arr_mask;
PyArrayObject *arr_adjacency;
PyArrayObject *arr_state;
PyArrayObject *arr_next_state;
double sum;
int counter_node, n_nodes;
/* PyArg_ParseTuple
* checks if from args, the pointers of type "O" can be extracted, and extracts them
*/
if (!PyArg_ParseTuple(args, "OOO:xor_masking_C", &mask, &adjacency, &state))
return NULL;
/*
* The pointer returned by PyArray_ContiguousFromObject is typecasted to
* …Run Code Online (Sandbox Code Playgroud)