在Cython中访问C函数

时间:2014-11-09 18:37:13

标签: c cython

我正在尝试在cython中使用C代码

example.c:

 #include <stdlib.h>
 #include <stdio.h>
 #include <math.h>

 double* reverseCoeffs(double* coeffs, int N) {
    double *revCoeffs = (double*) malloc(7 * sizeof(double));
    if (N < 7) {
       coeffs = (double *) realloc(coeffs, 7 * sizeof(double));
       while (N < 7) coeffs[N++] = (double) 0;
    }
    // The first coefficient is the linear part
    revCoeffs[0] = 1 / coeffs[0];
    revCoeffs[1] = -coeffs[1] / pow(coeffs[0], 3);
    revCoeffs[2] = (2 * pow(coeffs[1], 2) - coeffs[0] * coeffs[2]) / pow(coeffs[0], 5);
    free(coeffs);
    return revCoeffs;
}

这在C中运行得非常好但是当我在cython中使用它时会抛出错误。

example.pyx:

import numpy as np
cimport numpy as np
cdef extern from "reverseCoeffs.c":
  double* reverseCoeffs(double* coeffs, int N)
def cisr(np.ndarray[np.double_t,ndim=1] x, int N):
  cdef double* x_data = <double *>x.data
  cdef np.ndarray[np.double_t, ndim=1] res
  res = reverseCoeffs(x_data, N)
  return res

以下是我收到的错误:

running build_ext
cythoning test.pyx to test.c

Error compiling Cython file:
------------------------------------------------------------
...
cdef extern from "test.c":
    double* reverseCoeffs(double* coeffs, int N)
def cisr(np.ndarray[np.double_t,ndim=1] x, int N):
cdef double* x_data = <double *>x.data
cdef np.ndarray[np.double_t, ndim=1] res
res = reverseCoeffs(x_data, N)
                ^
------------------------------------------------------------

test.pyx:8:21: Cannot convert 'double *' to Python object
building 'pang' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-      prototypes -fPIC -I/home/sulabh/.local/lib/python2.7/site-packages/numpy/core/include  -I/home/sulabh/include/ -I/home/sulabh/anaconda/include/python2.7 -c test.c -o build/temp.linux-x86_64-2.7/test.o
test.c:1:2: error: #error Do not use this file, it is the result of a failed Cython   compilation.

错误:命令'gcc'因退出状态1而失败

0 个答案:

没有答案