From 6971285acfdc6d2467684a8945754673f092c3e1 Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 9 May 2017 08:31:13 +0200 Subject: [PATCH] s4:pyrpc: add pyrpc_PyStr_AsString() helper function This contains the logic that's currently used in the pidl generated python bindings. Moving this to a helper function will remove a lot of generated code. Signed-off-by: Stefan Metzmacher --- source4/librpc/rpc/pyrpc_util.c | 34 +++++++++++++++++++++++++++++++++ source4/librpc/rpc/pyrpc_util.h | 1 + 2 files changed, 35 insertions(+) diff --git a/source4/librpc/rpc/pyrpc_util.c b/source4/librpc/rpc/pyrpc_util.c index 8d5ec45817fd..aa996c032b39 100644 --- a/source4/librpc/rpc/pyrpc_util.c +++ b/source4/librpc/rpc/pyrpc_util.c @@ -424,6 +424,40 @@ PyObject *PyString_FromStringOrNULL(const char *str) return PyStr_FromString(str); } +const char *pyrpc_PyStr_AsString(TALLOC_CTX *mem_ctx, PyObject *value) +{ + const char *test_str = NULL; + const char *talloc_str = NULL; + PyObject *unicode = NULL; + + if (PyUnicode_Check(value)) { + unicode = PyUnicode_AsEncodedString(value, "utf-8", "ignore"); + if (unicode == NULL) { + PyErr_NoMemory(); + return NULL; + } + test_str = PyBytes_AS_STRING(unicode); + } else if (PyBytes_Check(value)) { + test_str = PyBytes_AS_STRING(value); + } else { + PyErr_Format(PyExc_TypeError, + "Expected string or unicode object, got %s", + Py_TYPE(value)->tp_name); + return NULL; + } + + talloc_str = talloc_strdup(mem_ctx, test_str); + if (unicode != NULL) { + Py_DECREF(unicode); + } + if (talloc_str == NULL) { + PyErr_NoMemory(); + return NULL; + } + + return talloc_str; +} + PyObject *pyrpc_import_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level, const void *in, const char *typename) { diff --git a/source4/librpc/rpc/pyrpc_util.h b/source4/librpc/rpc/pyrpc_util.h index 5a5f14de285d..6e70bf01b3d4 100644 --- a/source4/librpc/rpc/pyrpc_util.h +++ b/source4/librpc/rpc/pyrpc_util.h @@ -58,6 +58,7 @@ PyObject *py_return_ndr_struct(const char *module_name, const char *type_name, TALLOC_CTX *r_ctx, void *r); PyObject *PyString_FromStringOrNULL(const char *str); +const char *pyrpc_PyStr_AsString(TALLOC_CTX *mem_ctx, PyObject *value); PyObject *pyrpc_import_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level, const void *in, const char *typename); -- 2.34.1