Created
January 15, 2017 03:25
-
-
Save jiajunhuang/978bd2e761d696e776a18c417fa1b16c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cdef extern from "area.h": | |
cdef struct Square: | |
float length | |
float width | |
ctypedef Square *pSquare | |
cdef float calc_area(pSquare) | |
cdef float shared |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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