pyrpc: Add py_check_dcerpc_type().
[nivanova/samba-autobuild/.git] / source4 / librpc / rpc / pyrpc_util.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Python interface to DCE/RPC library - utility functions.
5
6    Copyright (C) 2010 Jelmer Vernooij <jelmer@samba.org>
7    Copyright (C) 2010 Andrew Tridgell <tridge@samba.org>
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include <Python.h>
24 #include "includes.h"
25 #include "librpc/rpc/pyrpc_util.h"
26
27 #ifndef Py_TYPE /* Py_TYPE is only available on Python > 2.6 */
28 #define Py_TYPE(ob)             (((PyObject*)(ob))->ob_type)
29 #endif
30
31 bool py_check_dcerpc_type(PyObject *obj, const char *module, const char *typename)
32 {
33         PyObject *mod;
34         PyTypeObject *type;
35         bool ret;
36
37         mod = PyImport_ImportModule(module);
38
39         if (mod == NULL) {
40                 PyErr_Format(PyExc_RuntimeError, "Unable to import %s to check type %s",
41                         module, typename);
42                 return NULL;
43         }
44
45         type = (PyTypeObject *)PyObject_GetAttrString(mod, typename);
46         Py_DECREF(mod);
47         if (type == NULL) {
48                 PyErr_Format(PyExc_RuntimeError, "Unable to find type %s in module %s",
49                         module, typename);
50                 return NULL;
51         }
52
53         ret = PyObject_TypeCheck(obj, type);
54         Py_DECREF(type);
55
56         if (!ret)
57                 PyErr_Format(PyExc_TypeError, "Expected type %s.%s, got %s",
58                         module, typename, Py_TYPE(obj)->tp_name);
59
60         return ret;
61 }