Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import ctypes
libfive = ctypes.cdll.LoadLibrary('build/libfive/src/libfive.dylib')
libfive.libfive_tree_x.restype = ctypes.c_void_p
libfive.libfive_tree_y.restype = ctypes.c_void_p
libfive.libfive_tree_delete.argtypes = [ctypes.c_void_p]
libfive.libfive_tree_binary.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p]
libfive.libfive_tree_binary.restype = ctypes.c_void_p
libfive.libfive_opcode_enum.argtypes = [ctypes.c_char_p]
libfive.libfive_opcode_enum.restype = ctypes.c_int
libfive.libfive_tree_const.argtypes = [ctypes.c_float]
libfive.libfive_tree_const.restype = ctypes.c_void_p
libfive.libfive_tree_print.argtypes = [ctypes.c_void_p]
libfive.libfive_tree_print.restype = ctypes.c_char_p
class Tree(object):
def __init__(self, ptr):
self.ptr = ptr
def __del__(self):
libfive.libfive_tree_delete(self.ptr)
@staticmethod
def x():
return Tree(libfive.libfive_tree_x())
@staticmethod
def y():
return Tree(libfive.libfive_tree_y())
@staticmethod
def const(f):
return Tree(libfive.libfive_tree_const(f))
@staticmethod
def opcode(op):
p = libfive.libfive_opcode_enum(op.encode('utf-8'))
if p == -1:
raise RuntimeError("Invalid opcode {}".format(op))
return p
def __add__(self, lhs):
if not isinstance(lhs, Tree):
lhs = self.const(lhs)
return Tree(libfive.libfive_tree_binary(
self.opcode('add'), self.ptr, lhs.ptr))
def __radd__(self, rhs):
if not isinstance(rhs, Tree):
rhs = self.const(rhs)
return Tree(libfive.libfive_tree_binary(
self.opcode('add'), rhs.ptr, self.ptr))
def __repr__(self):
''' WARNING: leaks the returned strings! '''
return 'Tree<{}>'.format(
libfive.libfive_tree_print(self.ptr).decode('utf-8'))
################################################################################
Python 3.7.0 (default, Jun 29 2018, 20:13:13)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: %run python_minimal.py
In [2]: 12.5
Out[2]: 12.5
In [3]: 12.5 + Tree.x()
Out[3]: Tree<(+ 12.5 x)>
In [4]: Tree.x() + 15
Out[4]: Tree<(+ x 15)>
In [5]: Tree.x() + 15 + Tree.y()
Out[5]: Tree<(+ x 15 y)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment