Wor*_*der 5 c python 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]
Run Code Online (Sandbox Code Playgroud)
然后,这些常量由模块提供的函数返回。我在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;
}
Run Code Online (Sandbox Code Playgroud)
我已经标记了有问题的部分。在将字符串常量添加到模块中之后,我PyModule_AddStringConstant(module, "FOO", "foo");如何才能PyObject*从方法中将它们作为a返回呢?退货时是否需要增加参考计数器?
由于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");
Run Code Online (Sandbox Code Playgroud)
要将其与您的函数结合起来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;
}
Run Code Online (Sandbox Code Playgroud)