Sort include order.
[gemrb.git] / gemrb / plugins / GUIScript / PythonHelpers.h
blob5802cc7697711f5e51090de834ea7568147329ea
1 /* GemRB - Infinity Engine Emulator
2 * Copyright (C) 2003 The GemRB Project
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 #ifndef PYTHON_HELPERS_H
20 #define PYTHON_HELPERS_H
22 #include "win32def.h" // For Logging
24 #include "Holder.h"
25 #include "Interface.h"
27 #ifdef WIN32
28 #ifdef _DEBUG
29 #undef _DEBUG
30 #include <Python.h>
31 #define _DEBUG
32 #else
33 #include <Python.h>
34 #endif
35 #else
36 #include <Python.h>
37 #endif
39 template <typename T>
40 class CObject : public Holder<T> {
41 private:
42 public:
43 operator PyObject* () const
45 if (Holder<T>::ptr) {
46 Holder<T>::ptr->acquire();
47 GUIScript *gs = (GUIScript *) core->GetGUIScriptEngine();
48 PyObject *obj = PyCObject_FromVoidPtrAndDesc(Holder<T>::ptr,const_cast<TypeID*>(&T::ID),PyRelease);
49 PyObject *tuple = PyTuple_New(1);
50 PyTuple_SET_ITEM(tuple, 0, obj);
51 return gs->ConstructObject(T::ID.description, tuple);
52 } else {
53 Py_INCREF( Py_None );
54 return Py_None;
57 CObject(PyObject *obj)
59 if (obj == Py_None)
60 return;
61 PyObject *id = PyObject_GetAttrString(obj, "ID");
62 if (id)
63 obj = id;
64 else
65 PyErr_Clear();
66 if (!PyCObject_Check(obj) || PyCObject_GetDesc(obj) != const_cast<TypeID*>(&T::ID)) {
67 printMessage("GUIScript","Bad CObject extracted.\n",LIGHT_RED);
68 return;
70 Holder<T>::ptr = static_cast<T*>(PyCObject_AsVoidPtr(obj));
71 Holder<T>::ptr->acquire();
72 if (id) {
73 Py_DECREF(id);
76 CObject(const Holder<T>& ptr)
77 : Holder<T>(ptr)
80 // This is here because of lookup order issues.
81 operator bool () const
83 return Holder<T>::ptr;
85 private:
86 static void PyRelease(void *obj, void *desc)
88 if (desc != const_cast<TypeID*>(&T::ID)) {
89 printMessage("GUIScript","Bad CObject deleted.\n",LIGHT_RED);
90 return;
92 static_cast<T*>(obj)->release();
96 template <typename T, class Container>
97 PyObject* MakePyList(const Container &source)
99 size_t size = source.size();
100 PyObject *list = PyList_New(size);
101 for (size_t i = 0; i < size; ++i) {
102 // SET_ITEM might be preferable to SetItem here, but MSVC6 doesn't like it.
103 PyList_SetItem(list, i, CObject<T>(source[i]));
105 return list;
108 #endif