Last active
January 19, 2017 08:32
-
-
Save ruoyu0088/47135d7726abfdc03a61f63d4696cb74 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
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) |
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
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 |
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 "square.h" | |
float glb_f; | |
float calc_area(sq a) { | |
float s; | |
s = a->length * a->width + glb_f; | |
return 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
struct Square { | |
float length; | |
float width; | |
}; | |
typedef struct Square *sq; | |
extern float glb_f; | |
float calc_area(sq a); |
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
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