s4:pyrpc: add pyrpc_PyStr_AsString() helper function
authorStefan Metzmacher <metze@samba.org>
Tue, 9 May 2017 06:31:13 +0000 (08:31 +0200)
committerStefan Metzmacher <metze@samba.org>
Mon, 18 Feb 2019 11:47:34 +0000 (12:47 +0100)
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 <metze@samba.org>
source4/librpc/rpc/pyrpc_util.c
source4/librpc/rpc/pyrpc_util.h

index 8d5ec45817fd6357728ae88d55f94c4ceec8d3a8..aa996c032b397e8cdb75408b8d599d2c126de697 100644 (file)
@@ -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)
 {
index 5a5f14de285d0e90b18a5865572d9c79f932e90e..6e70bf01b3d4fa2c5a70af666e0217ca458bc9a3 100644 (file)
@@ -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);