我想使用Python的C-API将我编写的Python库实现为C语言。在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*
?当我返回它们时,我需要增加引用计数吗?