I wanted to implement a library I have written for python in C using the C-API of python. In python I can declare "constants" in my module by just stating:
RED = "red" # Not really a constant, I know
BLUE = "blue" # but suitable, nevertheless
def solve(img_h):
# Awesome computations
return (RED, BLUE)[some_flag]
Those constants are then later returned by the functions offered by the module. I have some trouble doing the same thing in C. Here is what I got so far:
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;
}
I have already marked the problematic part. After I add string constants to the module with PyModule_AddStringConstant(module, "FOO", "foo");
how can I actually return them as a PyObject*
from my methods? Do I need to increase the ref-counter when I return them?