Python 包装期望C动态回调的C函数
我正试图围绕libedit编写一个包装器(一个BSD替代readline,使用稍微不同的API),有一种方法可以向C API添加一个命名函数 例如,在C中:Python 包装期望C动态回调的C函数,python,python-c-api,cpython,Python,Python C Api,Cpython,我正试图围绕libedit编写一个包装器(一个BSD替代readline,使用稍微不同的API),有一种方法可以向C API添加一个命名函数 例如,在C中: static unsigned char show_help(EditLine *e, int ch) { printf("Help"); } el = el_init(argv[0], stdin, stdout, stderr); el_set(el, EL_ADDFN, "help", "This is help", sh
static unsigned char show_help(EditLine *e, int ch) {
printf("Help");
}
el = el_init(argv[0], stdin, stdout, stderr);
el_set(el, EL_ADDFN, "help", "This is help", show_help);
el_set(el, EL_BIND, "\?", "help", NULL);
我调用el_set来添加一个函数,然后稍后绑定该函数
我找不到一个好方法来包装EL_ADDFN以动态绑定Python方法。我可以创建一组prenamed C函数,并将它们分别包装到python方法中,但我更愿意尽可能地模拟C API
有没有一种方法可以调用EL_ADDFN并确定它正在调用哪个python方法?试试这个:一个单一的处理函数(我将在下面描述)。包装EL_ADDFN,以便它记录名称到python函数的映射,但始终使用one handler函数。包装EL_BIND,以便它记录字符到函数名的映射。处理函数应该在角色到名称映射中查找ch参数,然后查找名称到函数映射,然后调用该函数。(如果必须在绑定之前调用ADDFN,则可以创建ch-to函数的映射,并直接在绑定包装器中填充该映射。) 在伪C中:
const char *chmap[256]; // initialize to zero
struct hashtable *namemap; // up to you to find a
// hashtable implementation that
// will take const char * and map to
// PyObject * (function object);
static unsigned char python_func(EditLine *e, int ch) {
const char *name = chmap[ch];
// check for errors
PyObject *func = lookup(namemap, name);
// check for errors
PyObject *editline = convert(e); // or whatever you have
PyObject *result = PyObject_CallFunctionObjArgs(func, NULL);
// check result, convert to unsigned char, and return
}
因此,ADDFN包装器填充哈希表,BIND操作符填充chmap