-
-
Notifications
You must be signed in to change notification settings - Fork 479
Expand file tree
/
Copy pathc callback.pyx
More file actions
74 lines (59 loc) · 1.35 KB
/
c callback.pyx
File metadata and controls
74 lines (59 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
setup.bat:
-----------
del cheese.pyd
call python "setup.py" build_ext --inplace
pause
run_cheese.py:
-----------------
import cheese
cheese.find()
setup.py:
-----------
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'callback',
ext_modules=[
Extension("cheese", ["cheese.pyx"]),
],
cmdclass = {'build_ext': build_ext}
)
"""
"""
cheese.pyx:
--------------
"""
# It can get even easier "Using Cython Declarations from C":
# http://docs.cython.org/src/userguide/external_C_code.html#using-cython-declarations-from-c
cdef extern from "cheesefinder.h":
ctypedef int (*cheesefunc)(char *name)
void find_cheeses(cheesefunc user_func)
def find():
find_cheeses(<cheesefunc>report_cheese)
# When using callbacks from C need to use GIL:
# http://docs.cython.org/src/userguide/external_C_code.html#acquiring-and-releasing-the-gil
cdef int report_cheese(char* name) with gil:
print("Found cheese: " + name)
return 0
"""
cheesefinder.h:
------------------
typedef int (*cheesefunc)(char *name);
void find_cheeses(cheesefunc user_func);
static char *cheeses[] = {
"cheddar",
"camembert",
"that runny one",
0
};
void find_cheeses(cheesefunc user_func) {
char **p = cheeses;
int r = 1;
while (r && *p) {
r = user_func(*p);
++p;
}
}
"""