Get rid of most system headers.
[gemrb.git] / gemrb / plugins / GUIScript / PythonHelpers.h
blobe0ed9d46944bf56f52bc14a91669677d8633b8f5
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 template <typename T>
28 class CObject : public Holder<T> {
29 private:
30 public:
31 operator PyObject* () const
33 if (Holder<T>::ptr) {
34 Holder<T>::ptr->acquire();
35 GUIScript *gs = (GUIScript *) core->GetGUIScriptEngine();
36 PyObject *obj = PyCObject_FromVoidPtrAndDesc(Holder<T>::ptr,const_cast<TypeID*>(&T::ID),PyRelease);
37 PyObject *tuple = PyTuple_New(1);
38 PyTuple_SET_ITEM(tuple, 0, obj);
39 return gs->ConstructObject(T::ID.description, tuple);
40 } else {
41 Py_INCREF( Py_None );
42 return Py_None;
45 CObject(PyObject *obj)
47 if (obj == Py_None)
48 return;
49 PyObject *id = PyObject_GetAttrString(obj, "ID");
50 if (id)
51 obj = id;
52 else
53 PyErr_Clear();
54 if (!PyCObject_Check(obj) || PyCObject_GetDesc(obj) != const_cast<TypeID*>(&T::ID)) {
55 printMessage("GUIScript","Bad CObject extracted.\n",LIGHT_RED);
56 return;
58 Holder<T>::ptr = static_cast<T*>(PyCObject_AsVoidPtr(obj));
59 Holder<T>::ptr->acquire();
60 if (id) {
61 Py_DECREF(id);
64 CObject(const Holder<T>& ptr)
65 : Holder<T>(ptr)
68 // This is here because of lookup order issues.
69 operator bool () const
71 return Holder<T>::ptr;
73 private:
74 static void PyRelease(void *obj, void *desc)
76 if (desc != const_cast<TypeID*>(&T::ID)) {
77 printMessage("GUIScript","Bad CObject deleted.\n",LIGHT_RED);
78 return;
80 static_cast<T*>(obj)->release();
84 template <typename T, class Container>
85 PyObject* MakePyList(const Container &source)
87 size_t size = source.size();
88 PyObject *list = PyList_New(size);
89 for (size_t i = 0; i < size; ++i) {
90 // SET_ITEM might be preferable to SetItem here, but MSVC6 doesn't like it.
91 PyList_SetItem(list, i, CObject<T>(source[i]));
93 return list;
96 #endif