forked from nanomsg/nnpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.py
71 lines (54 loc) · 1.88 KB
/
generate.py
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
from cffi import FFI
import os
INCLUDE = ['/usr/include/nanomsg', '/usr/local/include/nanomsg']
BLOCKS = {'{': '}', '(': ')'}
def header_files():
for dir in INCLUDE:
if os.path.exists(dir):
break
return {fn: os.path.join(dir, fn) for fn in os.listdir(dir)}
def functions(hfiles):
lines = []
for fn, path in hfiles.items():
with open(path) as f:
cont = ''
for ln in f:
if cont == ',':
lines.append(ln)
cont = ''
if cont in BLOCKS:
lines.append(ln)
if BLOCKS[cont] in ln:
cont = ''
if not (ln.startswith('NN_EXPORT')
or ln.startswith('typedef')):
continue
lines.append(ln)
cont = ln.strip()[-1]
return ''.join(ln[10:] if ln.startswith('NN_') else ln for ln in lines)
def symbols(ffi):
nanomsg = ffi.dlopen('nanomsg')
lines = []
for i in range(1024):
val = ffi.new('int*')
name = nanomsg.nn_symbol(i, val)
if name == ffi.NULL:
break
name = ffi.string(name).decode()
name = name[3:] if name.startswith('NN_') else name
lines.append('%s = %s' % (name, val[0]))
return '\n'.join(lines) + '\n'
def create_module():
hfiles = header_files()
# remove ws.h due to https://github.com/nanomsg/nanomsg/issues/467
hfiles.pop('ws.h', None)
ffi = FFI()
ffi.cdef(functions(hfiles))
ffi.set_source('_nnpy', '\n'.join('#include <%s>' % fn for fn in hfiles),
libraries=['nanomsg'], include_dirs=INCLUDE)
return ffi
ffi = create_module()
with open('nnpy/constants.py', 'w') as f:
f.write(symbols(ffi))
if __name__ == '__main__':
ffi.compile()