Skip to content

Instantly share code, notes, and snippets.

@ruoyu0088
Last active January 19, 2017 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ruoyu0088/47135d7726abfdc03a61f63d4696cb74 to your computer and use it in GitHub Desktop.
Save ruoyu0088/47135d7726abfdc03a61f63d4696cb74 to your computer and use it in GitHub Desktop.
from cffi import FFI
ffibuilder = FFI()
ffibuilder.set_source("_square",
r"""
#include "square.h"
""",
sources=["square.c"])
with open("square.h") as f:
ffibuilder.cdef(f.read())
if __name__ == "__main__":
ffibuilder.compile(verbose=True)
def get_c_declares(filename, fake_include):
from pycparser import parse_file, c_ast, c_generator
folder = path.dirname(filename)
ast = parse_file(filename, use_cpp=True, cpp_path="gcc",
cpp_args=["-E", "-I{}".format(folder), "-I{}".format(fake_include), "-DSIM_DEBUG"])
declares = []
generator = c_generator.CGenerator()
for child in ast.ext:
if isinstance(child, c_ast.FuncDef):
continue
declares.append(generator.visit(child))
code = ";\n".join(declares) + ";"
return code
#include "square.h"
float glb_f;
float calc_area(sq a) {
float s;
s = a->length * a->width + glb_f;
return s;
}
struct Square {
float length;
float width;
};
typedef struct Square *sq;
extern float glb_f;
float calc_area(sq a);
import _square
ffi = _square.ffi
lib = _square.lib
lib.glb_f = 10.0
rect = ffi.new("sq", {"length":10, "width":20})
rect.width = 30
print(lib.calc_area(rect))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment