包装期望C动态回调的C函数

2024-03-28 20:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试围绕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", show_help);
el_set(el, EL_BIND, "\?", "help", NULL);

我调用elu set来添加一个函数,然后稍后绑定该函数。你知道吗

我找不到一个好方法来允许我包装elu ADDFN来动态绑定Python方法。我可以创建一组prenamed C函数并将它们单独包装到python方法中,但我更希望尽可能地模拟capi。你知道吗

有没有办法调用elu ADDFN并确定它正在调用哪个python方法?你知道吗


Tags: 方法函数apireadlineshowhelpbsdstatic
1条回答
网友
1楼 · 发布于 2024-03-28 20:36:19

试试这个:一个单一的处理函数(我将在下面描述)。包装elu ADDFN,以便它记录名称到python函数的映射,但始终使用one handler函数。包装elu绑定,以便记录字符到函数名的映射。处理函数应该在character-to-name映射中查找ch参数,然后查找name-to-function映射,然后调用函数。(如果必须在绑定之前调用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 wrapper填充哈希表,BIND操作符填充chmap。你知道吗

相关问题 更多 >