X-Git-Url: https://sigrok.org/gitweb/?p=libsigrokdecode.git;a=blobdiff_plain;f=util.c;h=6164aaa91e87d95c398ab3bdb5c5b25dd3f51b40;hp=3aa0fd90a324ca5349c193f6129e6a858fbed2c1;hb=73191416cc24884ffab5f21cc3405c7757884fba;hpb=b2c19614a6c4eaa0170971d1261a1bb25212e277 diff --git a/util.c b/util.c index 3aa0fd9..6164aaa 100644 --- a/util.c +++ b/util.c @@ -19,55 +19,61 @@ */ #include "config.h" -#include /* First, so we avoid a _POSIX_C_SOURCE warning. */ +#include "sigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */ /** - * Helper function to handle Python strings. + * Helper function to get the value of a python object's attribute, + * returned as a newly allocated char *. * - * TODO: @param entries. + * @param py_obj The object to probe. + * @param key Name of the attribute to retrieve. + * @param outstr ptr to char * storage to be filled in. * * @return SRD_OK upon success, a (negative) error code otherwise. * The 'outstr' argument points to a malloc()ed string upon success. */ -int h_str(PyObject *py_res, PyObject *py_mod, const char *key, char **outstr) +int h_str(PyObject *py_obj, const char *key, char **outstr) { - PyObject *py_str; + PyObject *py_str, *py_encstr; char *str; int ret; - py_str = PyObject_GetAttrString(py_res, (char *)key); /* NEWREF */ - if (!py_str || !PyString_Check(py_str)) { - ret = SRD_ERR_PYTHON; /* TODO: More specific error? */ - goto err_h_decref_mod; + py_str = py_encstr = NULL; + str = NULL; + ret = SRD_OK; + + if (!(py_str = PyObject_GetAttrString(py_obj, (char *)key))) { + /* TODO: log level 4 debug message */ + ret = SRD_ERR_PYTHON; + goto err_out; } - /* - * PyString_AsString()'s returned string refers to an internal buffer - * (not a copy), i.e. the data must not be modified, and the memory - * must not be free()'d. - */ - if (!(str = PyString_AsString(py_str))) { - ret = SRD_ERR_PYTHON; /* TODO: More specific error? */ - goto err_h_decref_str; + if (!(py_encstr = PyUnicode_AsEncodedString(py_str, "utf-8", NULL))) { + /* TODO: log level 4 debug message */ + ret = SRD_ERR_PYTHON; + goto err_out; + } + if (!(str = PyBytes_AS_STRING(py_encstr))) { + /* TODO: log level 4 debug message */ + ret = SRD_ERR_PYTHON; + goto err_out; } if (!(*outstr = g_strdup(str))) { + /* TODO: log level 4 debug message */ ret = SRD_ERR_MALLOC; - goto err_h_decref_str; + goto err_out; } - Py_XDECREF(py_str); - - return SRD_OK; - -err_h_decref_str: - Py_XDECREF(py_str); -err_h_decref_mod: - Py_XDECREF(py_mod); +err_out: + if (py_str) + Py_XDECREF(py_str); + if (py_encstr) + Py_XDECREF(py_encstr); if (PyErr_Occurred()) - PyErr_Print(); /* Returns void. */ + PyErr_Print(); return ret; }