我想使用 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*
从我的方法?退货时是否需要增加参考计数器?