在只有numpy的cython中调用此函数的最佳方法是什么?
我不会使用ctypes,memcpy,malloc等。

功能1)

#include <stdio.h>
extern "C" void cfun(const void * indatav, int rowcount, int colcount,
void * outdatav);

void cfun(const void * indatav, int rowcount, int colcount, void *
outdatav) {
    //void cfun(const double * indata, int rowcount, int colcount,
double * outdata) {
    const double * indata = (double *) indatav;
    double * outdata = (double *) outdatav;
    int i;
    puts("Here we go!");
    for (i = 0; i < rowcount * colcount; ++i) {
        outdata[i] = indata[i] * 4;
    }
    puts("Done!");
}

功能2)
#include <stdio.h>

extern "C" __declspec(dllexport) void cfun(const double ** indata, int
rowcount, int colcount, double ** outdata) {
    for (int i = 0; i < rowcount; ++i) {
        for (int j = 0; j < colcount; ++j) {
            outdata[i][j] = indata[i][j] * 4;
        }
    }
}

崔元俊

最佳答案

您可以通过将其声明为extern来直接从Cython中“调用”该函数。

cdef extern from "mylibraryheader.h":
    void cfun1(void* indatav, int rowcount, int colcount, void* outdatav)
    void cfun2(double** indata, int rowcount, int colcount, doubke** outdata)

现在,您可以像在C/C++中那样调用这些函数。请注意,Cython中没有const关键字,您可以忽略它。不幸的是,我无法为您提供有关如何将NumPy数组转换为double数组的示例。但是,这是从 double 列表中运行它的示例。
cdef extern from "mylibraryheader.h":
    void cfun1(void* indatav, int rowcount, int colcount, void* outdatav)
    void cfun2(double** indata, int rowcount, int colcount, double** outdata)

cdef extern from "stdlib.h":
    ctypedef int size_t
    void* malloc(size_t)
    void free(void*)

def py_cfunc1(*values):
    cdef int i = 0
    cdef int size = sizeof(double)*len(values)
    cdef double* indatav = <double*> malloc(size)
    cdef double* outdatav = <double*> malloc(size)
    cdef list outvalues = []
    for v in values:
        indatav[i] = <double>v
        i += 1
    cfun1(<void*>indatav, 1, len(values), <void*>outdatav)
    for 0 <= i < len(values):
        outvalues.append(outdatav[i])
    return outvalues

注意:未经测试

09-07 05:37