Python C-API访问字符串常量

时间:2015-06-02 20:46:30

标签: python c interface python-c-api

我想使用python的C-API实现我在C中为python编写的库。在python中,我可以通过声明:

在我的模块中声明“常量”
RED = "red"   # Not really a constant, I know
BLUE = "blue" # but suitable, nevertheless

def solve(img_h):
    # Awesome computations
    return (RED, BLUE)[some_flag]

然后,这些常量将由模块提供的函数返回。我在C中做同样的事情有些麻烦。这是我到目前为止所得到的:

PyMODINIT_FUNC
PyInit_puzzler(void)
{
    PyObject* module = PyModule_Create(&Module);
    (void) PyModule_AddStringConstant(module, "BLUE",   "blue");
    (void) PyModule_AddStringConstant(module, "RED",    "red");
    return module;
}

PyObject* solve(PyObject* module, PyObject* file_handle)
{
    // Do some awesome computations based on the file
    // Involves HUGE amounts of memory management, thus efficient in C
    // PROBLEM: How do I return the StringConstants from here?
    return some_flag ? BLUE : RED;
}

我已经标记了有问题的部分。在我使用PyModule_AddStringConstant(module, "FOO", "foo");向模块添加字符串常量后,如何从我的方法中将它们作为PyObject*实际返回?我退货时是否需要增加参考计数器?

1 个答案:

答案 0 :(得分:4)

由于PyModule_AddStringConstant(module, name, value)将常量添加到模块,因此它应该可以从模块的字典中获得,该字典可以使用PyModule_GetDict(module)获取。然后,您可以使用PyDict_GetItemString(dict, key)通过其字典访问模块中的任何属性。这是您可以从模块中访问常量的方法(在定义之后):

// Get module dict. This is a borrowed reference.
PyObject* module_dict = PyModule_GetDict(module);

// Get BLUE constant. This is a borrowed reference.
PyObject* BLUE = PyDict_GetItemString(module_dict, "BLUE");

// Get RED constant. This is a borrowed reference.
PyObject* RED = PyDict_GetItemString(module_dict, "RED");

要将此功能置于您的solve()功能的上下文中,您需要类似的内容:

PyObject* solve(PyObject* module, PyObject* file_handle)
{
    // Do some awesome computations based on the file
    // Involves HUGE amounts of memory management, thus efficient in C

    // Return string constant at the end.
    PyObject* module_dict = PyModule_GetDict(module);
    PyObject* constant = NULL;
    if (some_flag) {
        // Return BLUE constant. Since BLUE is a borrowed 
        // reference, increment its reference count before 
        // returning it.
        constant = PyDict_GetItemString(module_dict, "BLUE");
        Py_INCREF(constant);
    } else {
        // Return RED constant. Since RED is a borrowed 
        // reference, increment its reference count before 
        // returning it.
        constant = PyDict_GetItemString(module_dict, "RED");
        Py_INCREF(constant);
    }

    // NOTE: Before you return, make sure to release any owned
    // references that this function acquired. `module_dict` does
    // not need to be released because it is merely "borrowed".

    // Return the constant (either BLUE or RED) as an owned
    // reference. Whatever calls `solve()` must make sure to
    // release the returned reference with `Py_DECREF()`.
    return constant;
}