blob: b6de2fb8017c61dffb450b598e5bfa31ca62ed2d [file] [log] [blame]
Bert Vermeulenb2c19612011-12-04 10:33:02 +01001/*
2 * This file is part of the sigrok project.
3 *
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2011 Bert Vermeulen <bert@biot.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21#include "config.h"
22#include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
23
24
25/**
26 * Helper function to handle Python strings.
27 *
28 * TODO: @param entries.
29 *
30 * @return SRD_OK upon success, a (negative) error code otherwise.
31 * The 'outstr' argument points to a malloc()ed string upon success.
32 */
33int h_str(PyObject *py_res, PyObject *py_mod, const char *key, char **outstr)
34{
Bert Vermeulen5f802ec2011-12-27 22:15:53 +010035 PyObject *py_str, *py_encstr;
Bert Vermeulenb2c19612011-12-04 10:33:02 +010036 char *str;
37 int ret;
38
Bert Vermeulen5f802ec2011-12-27 22:15:53 +010039 if (!(py_str = PyObject_GetAttrString(py_res, (char *)key))) {
Bert Vermeulenb2c19612011-12-04 10:33:02 +010040 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
41 goto err_h_decref_mod;
42 }
43
44 /*
Bert Vermeulen5f802ec2011-12-27 22:15:53 +010045 * PyBytes_AsString()'s returned string refers to an internal buffer
Bert Vermeulenb2c19612011-12-04 10:33:02 +010046 * (not a copy), i.e. the data must not be modified, and the memory
47 * must not be free()'d.
48 */
Bert Vermeulen5f802ec2011-12-27 22:15:53 +010049 if (!(py_encstr = PyUnicode_AsEncodedString(py_str, "utf-8", NULL))) {
50 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
51 goto err_h_decref_str;
52 }
53 if (!(str = PyBytes_AS_STRING(py_encstr))) {
Bert Vermeulenb2c19612011-12-04 10:33:02 +010054 ret = SRD_ERR_PYTHON; /* TODO: More specific error? */
55 goto err_h_decref_str;
56 }
57
58 if (!(*outstr = g_strdup(str))) {
59 ret = SRD_ERR_MALLOC;
60 goto err_h_decref_str;
61 }
62
63 Py_XDECREF(py_str);
64
65 return SRD_OK;
66
67err_h_decref_str:
68 Py_XDECREF(py_str);
69err_h_decref_mod:
70 Py_XDECREF(py_mod);
71
72 if (PyErr_Occurred())
73 PyErr_Print(); /* Returns void. */
74
75 return ret;
76}
77