Python C-API access String constants -
i wanted implement library have written python in c using c-api of python. in python can declare "constants" in module stating:
red = "red" # not constant, know blue = "blue" # suitable, nevertheless def solve(img_h): # awesome computations return (red, blue)[some_flag]
those constants later returned functions offered module. have trouble doing same thing in c. here got 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) { // awesome computations based on file // involves huge amounts of memory management, efficient in c // problem: how return stringconstants here? return some_flag ? blue : red; }
i have marked problematic part. after add string constants module pymodule_addstringconstant(module, "foo", "foo");
how can return them pyobject*
methods? need increase ref-counter when return them?
since pymodule_addstringconstant(module, name, value) adds constant module, should available module's dictionary can acquired pymodule_getdict(module). can access attribute module via dictionary using pydict_getitemstring(dict, key) how can access constants module (after definitions):
// module dict. borrowed reference. pyobject* module_dict = pymodule_getdict(module); // blue constant. borrowed reference. pyobject* blue = pydict_getitemstring(module_dict, "blue"); // red constant. borrowed reference. pyobject* red = pydict_getitemstring(module_dict, "red");
to put context solve()
function, want similar to:
pyobject* solve(pyobject* module, pyobject* file_handle) { // awesome computations based on file // involves huge amounts of memory management, efficient in c // return string constant @ end. pyobject* module_dict = pymodule_getdict(module); pyobject* constant = null; if (some_flag) { // return blue constant. since blue borrowed // reference, increment reference count before // returning it. constant = pydict_getitemstring(module_dict, "blue"); py_incref(constant); } else { // return red constant. since red borrowed // reference, increment reference count before // returning it. constant = pydict_getitemstring(module_dict, "red"); py_incref(constant); } // note: before return, make sure release owned // references function acquired. `module_dict` // not need released because merely "borrowed". // return constant (either blue or red) owned // reference. whatever calls `solve()` must make sure // release returned reference `py_decref()`. return constant; }
Comments
Post a Comment