How to get a char* from a PyObject which points to a string

可紊 提交于 2019-12-05 19:20:44

First you encode it, then you retrieve it. Don't forget to decref the temporary.

Here is my portable recipe for it, which makes use the default encoding, where that is applicable. It assumes you start with a PyObject*, named o. If you still have your input tuple from the function call, you can skip the first 2 lines.

PyObject* args = Py_BuildValue("(O)", o);
/* Py_DECREF(o); if o is not borrowed */
if (!args) return 0;
const char* s = 0;
if (!PyArg_ParseTuple(args, "s", &s)) {
  Py_DECREF(args);
  return 0;
}

/* s now points to a const char* - use it, delete args when done */

Py_DECREF(args);

PS: I have not tested it, but it should work with older versions of Python as well. There is nothing on it which is version specific.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!