Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I call this function in cython?

what is the best way to call this function in cython with only numpy? I am not going to 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

like image 614
wonjun Avatar asked Nov 04 '22 08:11

wonjun


1 Answers

You can 'call' the 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)

You can now call these functions like in C/C++. Note that there is no const keyword in Cython, you can leave it out. Unfortunately I can not give you an example of how to convert the NumPy array into an array of double. But here is an example of running it 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: Untested

like image 50
Niklas R Avatar answered Nov 09 '22 08:11

Niklas R