python如何返回数组的行数_如何返回数组c到Python?

I wrote a Python/C extension function that was called by Python, How can return an 2d array int[][] to Python?

static PyObject* inference_function(PyObject *self, PyObject *args)

{

PyObject* doc_lst;

int K,V;

double alpha,beta;

int n_iter;

if (!PyArg_ParseTuple(args, "Oiiddi", &doc_lst, &K,&V, &alpha,&beta,&n_iter))

{

printf("传入参数错误!\n");

return NULL;

}

return Py_BuildValue("i", 1);

}

解决方案

What kind of array are you using? One way, which I find convenient, is to use numpy arrays, and modify the data in place. Numpy already has a lot of great operations for manipulating integer arrays, so this is handy if you're trying to add some additional functionality.

Step 1: link your C extension to numpy

on windows, this is something like

#include "C:\Python34/Lib/site-packages/numpy/core/include/numpy/arrayobject.h"

on osx it's something like

#include "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/numpy/core/include/numpy/arrayobject.h"

Step 2: grab the pointer to the data. This is surprisingly easy

int* my_data_to_modify;

if (PyArg_ParseTuple(args, "O", &numpy_tmp_array)){

/* Point our data to the data in the numpy pixel array */

my_data_to_modify = (int*) numpy_tmp_array->data;

}

... /* do interesting things with your data */

2D numpy array in C

When you work with data this way, you can allocate it as a 2d array, e.g.

np.random.randint( 0, 100, (100,2) )

or all zeros if you want a blank slate

But all C cares about is contiguous data, which means you can loop through it by the lenght of a "row" and modify it as if it were a 2D array

for example, if you were passing in colors in rgb form, e.g., a 100x3 array of them, you would consider

int num_colors = numpy_tmp_array2->dimensions[0]; /* This gives you the column length */

int band_size = numpy_tmp_array2->dimensions[1]; /* This gives you the row length */

for ( i=0; i < num_colors * band_size; i += band_size ){

r = my_data[i];

g = my_data[i+1];

b = my_data[i+2];

}

To modify the data in place, just change a value in the data array. On the Python side, the numpy array will have the changed value.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值