Below is a simple C program square.c
, which is a simplification of a complex one:
#include <stdio.h>
#include <stdlib.h>
struct Square {
float length;
float width;
};
typedef struct Square *sq;
float calc_area(sq a) {
float s;
s = a->length * a->width;
return s;
}
int main() {
sq a;
a = malloc(sizeof(struct Square));
a->length = 10.0;
a->width = 3.0;
printf("%f\n", calc_area(a));
free(a);
}
I want to wrap the calc_area()
function and call it in Python. I am not quite familiar with C
nor Cython
, but it seems that the difficulty is that the argument of calc_area()
is a pointer struct.
I tried to use Cython, and below is my effort:
First, I wrote a header file square.h
:
#include <stdio.h>
#include <stdlib.h>
struct Square {
float length;
float width;
};
typedef struct Square *sq;
float calc_area(sq a);
Second, I wrote the square_wrapper.pyx
as below
cdef extern from 'square.h':
struct Square:
float length
float width
ctypedef struct Square *sq
float calc_area(sq a)
def c_area(a):
return calc_area(sq a)
It seems that ctypedef struct Square *sq
is not correct, but I have no idea how to modify it - this is the first time I try to wrap a C program and I cannot find similar examples to my case.
How could I fix this using Cython or any other tools? Thanks in advance!