Skip to content

Instantly share code, notes, and snippets.

@tito
Forked from Kovak/cython_callback_binding.pyx
Last active December 23, 2015 08:19
Show Gist options
  • Save tito/6606835 to your computer and use it in GitHub Desktop.
Save tito/6606835 to your computer and use it in GitHub Desktop.
constraint_handlers = {}
from cpython.ref cimport PyObject
cdef void _call_constraint_presolve_func(cpConstraint *constraint, cpSpace *space):
global constraint_handlers
global current_spaces
py_space = current_spaces[0]
py_constraint = <object><void *>constraint.data
constraint_dict = constraint_handlers[py_constraint]
constraint_dict['pre_solve'](py_constraint, py_space)
cdef class Constraint:
def __init__(self, args):
self._constraint = cpConstraint()
# XXX maybe void* is not necessary if cython recognize cpDataPointer as void*.
# Because the constraint C struct data contain self, there is no need to store self in the dict
# Just use self as a key.
# If "self" cannot be used as a key, use its memory location/pointer: id(self)
self._constraint.data = <cpDataPointer><void *>self
global constraint_handlers
constraint_handlers[self] = {}
def __dealloc__(self):
global constraint_handlers
del constraint_handlers[self]
property pre_solve:
def __set__(self, func):
self._set_py_presolve_handler(func)
self._constraint.preSolve = _call_constraint_presolve_func
def _set_py_presolve_handler(self, presolve_func):
global constraint_handlers
constraint_handlers[self]['pre_solve'] = presolve_func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment