Skip to content

Commit b278dff

Browse files
author
wusspuss
committed
Add get_callback function to get the python callable registered with register_callback
1 parent 52c882b commit b278dff

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

generic/tohil.c

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4541,6 +4541,27 @@ tohil_register_callback(PyObject *m, PyObject *args, PyObject *kwargs)
45414541
Py_RETURN_NONE;
45424542
}
45434543

4544+
static PyObject *
4545+
tohil_get_callback(PyObject *m, PyObject *args, PyObject *kwargs)
4546+
{
4547+
Tcl_Interp *interp = tohilstate(m)->interp;
4548+
Tcl_CmdInfo cmdinfo;
4549+
char * name;
4550+
static char *kwlist[] = {"name", NULL};
4551+
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &name)) {
4552+
return NULL;
4553+
}
4554+
if (!Tcl_GetCommandInfo(interp, name, &cmdinfo)) {
4555+
PyErr_SetString(PyExc_KeyError, "no such command");
4556+
return NULL;
4557+
}
4558+
if (cmdinfo.objProc == PythonCmd) {
4559+
return ((PythonCmd_ClientData *) cmdinfo.objClientData)->func;
4560+
} else {
4561+
PyErr_SetString(PyExc_KeyError, "Not a python callback ");
4562+
return NULL;
4563+
}
4564+
}
45444565
//
45454566
// python C extension structure defining functions
45464567
//
@@ -4561,6 +4582,8 @@ static PyMethodDef TohilMethods[] = {
45614582
{"result", (PyCFunction)tohil_result, METH_VARARGS | METH_KEYWORDS, "return the tcl interpreter result object"},
45624583
{"register_callback", (PyCFunction)tohil_register_callback, METH_VARARGS | METH_KEYWORDS,
45634584
"Register a Python callable so it can be called directly from Tcl as a command"},
4585+
{"get_callback", (PyCFunction)tohil_get_callback, METH_VARARGS | METH_KEYWORDS,
4586+
"Get the Python callable from a Tcl command registered with tohil.register_callback"},
45644587
{NULL, NULL, 0, NULL} /* Sentinel */
45654588
};
45664589

tests/test_register.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,7 @@ def setflag():
5151
time.sleep(.05)
5252
assert flag
5353

54+
def test_register_get(self):
55+
func = lambda: None
56+
tohil.register_callback("func", func)
57+
self.assertEqual(tohil.get_callback("func"), func)

0 commit comments

Comments
 (0)