c python 传参数 数组_将数组从c传输到python

我正在将一个双数组从c函数传递给

python函数.我的代码是:

C代码:

double *compute(int size, const double a[])

{

double* array;

array = malloc(sizeof(double)*size);

for (int i=0; i

{

array[i] = 3*a[i];

}

//printf("Array in compute-function is: \n[");

//for(int i = 0; i < size; i++)

//printf("%f, ", array[i]);

//printf("]\n");

return array;

}

PYX代码:

cdef class ArrayWrapper:

cdef void* data_ptr

cdef int size

cdef set_data(self, int size, void* data_ptr):

""" Set the data of the array

This cannot be done in the constructor as it must recieve C-level

arguments.

Parameters:

-----------

size: int

Length of the array.

data_ptr: void*

Pointer to the data

"""

self.data_ptr = data_ptr

self.size = size

def __array__(self):

""" Here we use the __array__ method, that is called when numpy

tries to get an array from the object."""

cdef np.npy_intp shape[1]

shape[0] = self.size

# Create a 1D array, of length 'size'

ndarray = np.PyArray_SimpleNewFromData(1, shape,

np.NPY_INT, self.data_ptr)

return ndarray

def __dealloc__(self):

""" Frees the array. This is called by Python when all the

references to the object are gone. """

free(self.data_ptr)

def py_compute(int size, np.ndarray[np.double_t,ndim=1] a):

""" Python binding of the 'compute' function in 'GNLSE_RHS.c' that does

not copy the data allocated in C.

"""

cdef double *array

cdef np.ndarray ndarray

# Call the C function

array = compute(size, a.data)

array_wrapper = ArrayWrapper()

array_wrapper.set_data(size, array)

ndarray = np.array(array_wrapper, copy=False)

# Assign our object to the 'base' of the ndarray object

ndarray.base = array_wrapper

# Increment the reference count, as the above assignement was done in

# C, and Python does not know that there is this additional reference

Py_INCREF(array_wrapper)

return ndarray

Python代码:

for i in xrange(10):

x[i] = i;

a = cython_wrapper.py_compute(10, x)

print a

但我的结果是

[ 0 0 0 1074266112 0 1075314688 0 1075970048 0 1076363264]

而不是预期的

[ 0. 3. 6. 9. 12. 15. 18. 21. 24. 27.]

我的错误在哪里?我认为它与有问题的指针传输有关,但我不确定.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值