How can I call this function in cython?

What is the best way to call this function in cython with just numpy? I will not use ctypes, memcpy, malloc, etc.

function 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!");
}

function 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;
        }
    }
}

Wonjun, Choi

+5
source share
2 answers

You can โ€œcallโ€ a function directly from Cython by declaring it as extern.

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)

Now you can call these functions, as in C / C ++. Please note that in Cython there is no const keyword, you can leave it. Unfortunately, I cannot give you an example of how to convert a NumPy array to a double array. But here is an example of starting from a list of doubles.

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

Note: Unverified

+2
source

cython - cython - . 1):

cimport numpy as np

def cfun(np.ndarray indata, int rowcount, int colcount, np.ndarray outdata):
    cdef int i
    print("Here we go!")
    for i in range(rowcount * colcount):
        outdata[i] = indata[i] * 4
    print("Done!")

, ctypes . swig .

0

All Articles