From 82acbfdc322b736e0f78ccc76de3a8ec7d863ed8 Mon Sep 17 00:00:00 2001 From: wusspuss Date: Fri, 28 Jan 2022 14:13:58 +1000 Subject: [PATCH] Add get_callback function to get the python callable registered with register_callback --- generic/tohil.c | 23 +++++++++++++++++++++++ pysrc/tohil/__init__.py | 1 + tests/test_register.py | 4 ++++ 3 files changed, 28 insertions(+) diff --git a/generic/tohil.c b/generic/tohil.c index 277ae7d..33e15cc 100644 --- a/generic/tohil.c +++ b/generic/tohil.c @@ -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 // @@ -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 */ }; diff --git a/pysrc/tohil/__init__.py b/pysrc/tohil/__init__.py index fb447d6..17ab427 100644 --- a/pysrc/tohil/__init__.py +++ b/pysrc/tohil/__init__.py @@ -293,6 +293,7 @@ def rivet(): incr, result, register_callback, + get_callback, __version__, ) diff --git a/tests/test_register.py b/tests/test_register.py index 21120c8..197284b 100644 --- a/tests/test_register.py +++ b/tests/test_register.py @@ -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)