Skip to content

Commit

Permalink
Add get_callback function to get the python callable registered with …
Browse files Browse the repository at this point in the history
…register_callback
  • Loading branch information
wusspuss committed Feb 1, 2022
1 parent 52c882b commit 82acbfd
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
23 changes: 23 additions & 0 deletions generic/tohil.c
Original file line number Diff line number Diff line change
Expand Up @@ -4541,6 +4541,27 @@ tohil_register_callback(PyObject *m, PyObject *args, PyObject *kwargs)
Py_RETURN_NONE;
}

static PyObject *
tohil_get_callback(PyObject *m, PyObject *args, PyObject *kwargs)
{
Tcl_Interp *interp = tohilstate(m)->interp;
Tcl_CmdInfo cmdinfo;
char * name;
static char *kwlist[] = {"name", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &name)) {
return NULL;
}
if (!Tcl_GetCommandInfo(interp, name, &cmdinfo)) {
PyErr_SetString(PyExc_KeyError, "no such command");
return NULL;
}
if (cmdinfo.objProc == PythonCmd) {
return ((PythonCmd_ClientData *) cmdinfo.objClientData)->func;
} else {
PyErr_SetString(PyExc_KeyError, "Not a python callback ");
return NULL;
}
}
//
// python C extension structure defining functions
//
Expand All @@ -4561,6 +4582,8 @@ static PyMethodDef TohilMethods[] = {
{"result", (PyCFunction)tohil_result, METH_VARARGS | METH_KEYWORDS, "return the tcl interpreter result object"},
{"register_callback", (PyCFunction)tohil_register_callback, METH_VARARGS | METH_KEYWORDS,
"Register a Python callable so it can be called directly from Tcl as a command"},
{"get_callback", (PyCFunction)tohil_get_callback, METH_VARARGS | METH_KEYWORDS,
"Get the Python callable from a Tcl command registered with tohil.register_callback"},
{NULL, NULL, 0, NULL} /* Sentinel */
};

Expand Down
1 change: 1 addition & 0 deletions pysrc/tohil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ def rivet():
incr,
result,
register_callback,
get_callback,
__version__,
)

Expand Down
4 changes: 4 additions & 0 deletions tests/test_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,7 @@ def setflag():
time.sleep(.05)
assert flag

def test_register_get(self):
func = lambda: None
tohil.register_callback("func", func)
self.assertEqual(tohil.get_callback("func"), func)

0 comments on commit 82acbfd

Please sign in to comment.