这个问题在很多地方都有描述,但我就是无法让它工作。我正在从Cython调用一个C++函数:
cimport numpy as np
cdef extern from "test.h" namespace "mytest":
void test(double *A, int m)
cdef int foo():
cdef np.ndarray[double,mode="c"] a = np.array([1,2,3,4,5],dtype=float)
# pass ptr to first element of 'a'
test(&a[0], len(a))
return 0
foo()
test.cpp 就是:
#include <stdio.h>
namespace mytest {
void test(double *A, int m)
{
for (int i = 0; i < m; i++)
{
printf("%d is %f\n", i, A[i]);
}
}
}
test.h文件仅包含:
namespace mytest {
void test(double *A, int m);
}
这似乎可行,但什么时候需要使用np.ascontiguousarray
?只做以下操作是否足够:
cdef np.ndarray[double,mode="c"] a = np.array([1,2,3,4,5],dtype=float)
或者你需要:
cdef np.ndarray[double,mode="c"] a = np.ascontiguousarray(np.array([1,2,3,4,5],dtype=float))
其次,更重要的是,如何将此推广到2维数组?
处理2维数组
以下是我尝试将2维numpy数组传递给不起作用的C++代码:
cdef np.ndarray[double,mode="c",ndim=2] a = np.array([[1,2],[3,4]],dtype=float)
这被称为:
test(&a[0,0], a.shape[0], a.shape[1])
在 CPP 代码中:
void test(double *A, int m, int n)
{
printf("reference 0,0 element\n");
printf("%f\n", A[0][0]);
}
更新:
正确的答案是对数组使用线性索引,而不是 [][]
语法。打印二维数组的正确方式是:
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%d, %d is %f\n", i, j, A[i*m + j]);
}
}
A
进行了两次解引用。对于一个二维数组,你可能需要手动进行索引算术运算。例如,如果你有一个C连续的m x n数组,并且你想要做NumPy的A[i,j]
的C等价操作,你需要做的是A[m*i+j]
而不是A[0][0]
。两次解引用指针可能会导致Python崩溃。 - IanHm
是行数。当您为指针指定类型时,数据类型会得到处理。我将举一个快速的例子。 - IanH&s[0]
语法传递给C)。 - jfs