Skip to content

Instantly share code, notes, and snippets.

@jiajunhuang
Created January 15, 2017 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jiajunhuang/978bd2e761d696e776a18c417fa1b16c to your computer and use it in GitHub Desktop.
Save jiajunhuang/978bd2e761d696e776a18c417fa1b16c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include "area.h"
float shared = 1.0;
float calc_area(pSquare s) {
return s->length * s->width + shared;
}
int main(void) {
pSquare s = (pSquare)malloc(sizeof(struct Square));
if (s == NULL) {
printf("memory not enough");
exit(1);
}
s->length = 10.0;
s->width = 3.0;
printf("area of the square: %f\n", calc_area(s));
free(s);
}
#ifndef _AREA_H
#define _AREA_H
struct Square {
float length;
float width;
};
typedef struct Square *pSquare;
float calc_area(pSquare);
extern float shared;
#endif /* area.h */
cdef extern from "area.h":
cdef struct Square:
float length
float width
ctypedef Square *pSquare
cdef float calc_area(pSquare)
cdef float shared
from cpython.mem cimport PyMem_Malloc, PyMem_Free
cimport carea
cdef class Square:
cdef carea.pSquare _square
def __cinit__(self, length, width, shared=1.0):
self._square = <carea.pSquare>PyMem_Malloc(sizeof(carea.Square))
if not self._square:
raise MemoryError("Memory not enough")
self._square.length = length
self._square.width = width
carea.shared = shared
def __dealloc__(self):
PyMem_Free(self._square)
cpdef float calc_area(self):
return carea.calc_area(self._square)
cdef float get_shared(self):
return carea.shared
cdef void set_shared(self, float value):
carea.shared = value
@property
def shared(self):
return self.get_shared()
@shared.setter
def shared(self, value):
self.set_shared(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment