1

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!

InfNorm
  • 19
  • 2
  • Pl. refer to the below link http://docs.cython.org/en/latest/src/tutorial/external.html. Also this is answered in stack overflow link given below http://stackoverflow.com/questions/3968499/how-to-embed-c-code-in-python-program – shri Jan 12 '17 at 07:34
  • Hi shri, thank you for the reply. But after reading the links you posted, I still cannot find anything similar to my case, in which the argument of the function is a pointer struct. Maybe I just don't understand quite well, but I think it would be much helpful if someone could give some hints about my example here. Thanks! – InfNorm Jan 12 '17 at 07:47
  • @InfNorm This link is probably more relevant: http://cython.readthedocs.io/en/latest/src/tutorial/clibraries.html. The question does show very little evidence that you're read through the documentation. – DavidW Jan 12 '17 at 10:08

0 Answers0