Files
dragonpilot/common/ffi_wrapper.py

50 lines
1.2 KiB
Python
Raw Normal View History

2018-08-19 20:36:37 -07:00
import os
import sys
import fcntl
import hashlib
from cffi import FFI
2019-04-23 01:41:19 +00:00
def ffi_wrap(name, c_code, c_header, tmpdir="/tmp/ccache", cflags="", libraries=None):
2019-03-26 01:09:18 -07:00
if libraries is None:
libraries = []
2018-08-19 20:36:37 -07:00
cache = name + "_" + hashlib.sha1(c_code).hexdigest()
try:
os.mkdir(tmpdir)
except OSError:
pass
fd = os.open(tmpdir, 0)
fcntl.flock(fd, fcntl.LOCK_EX)
try:
sys.path.append(tmpdir)
try:
mod = __import__(cache)
except Exception:
2019-04-23 01:41:19 +00:00
print("cache miss {0}".format(cache))
2018-10-21 15:00:31 -07:00
compile_code(cache, c_code, c_header, tmpdir, cflags, libraries)
2018-08-19 20:36:37 -07:00
mod = __import__(cache)
finally:
os.close(fd)
return mod.ffi, mod.lib
2019-03-26 01:09:18 -07:00
def compile_code(name, c_code, c_header, directory, cflags="", libraries=None):
if libraries is None:
libraries = []
2018-08-19 20:36:37 -07:00
ffibuilder = FFI()
2018-10-21 15:00:31 -07:00
ffibuilder.set_source(name, c_code, source_extension='.cpp', libraries=libraries)
2018-08-19 20:36:37 -07:00
ffibuilder.cdef(c_header)
os.environ['OPT'] = "-fwrapv -O2 -DNDEBUG -std=c++11"
2018-10-21 15:00:31 -07:00
os.environ['CFLAGS'] = cflags
2018-08-19 20:36:37 -07:00
ffibuilder.compile(verbose=True, debug=False, tmpdir=directory)
2019-03-26 01:09:18 -07:00
2018-08-19 20:36:37 -07:00
def wrap_compiled(name, directory):
sys.path.append(directory)
mod = __import__(name)
return mod.ffi, mod.lib