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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With