PyLucene 3.4.0-1 import
[pylucene.git] / jcc / jcc / sources / JObject.h
1 /*
2  *   Copyright (c) 2007-2008 Open Source Applications Foundation
3  *
4  *   Licensed under the Apache License, Version 2.0 (the "License");
5  *   you may not use this file except in compliance with the License.
6  *   You may obtain a copy of the License at
7  *
8  *       http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *   Unless required by applicable law or agreed to in writing, software
11  *   distributed under the License is distributed on an "AS IS" BASIS,
12  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *   See the License for the specific language governing permissions and
14  *   limitations under the License.
15  */
16
17 #ifndef _JObject_H
18 #define _JObject_H
19
20 #include <stdio.h>
21 #include "JCCEnv.h"
22
23 class _DLL_EXPORT JObject {
24 public:
25     jobject this$;
26     int id;  /* zero when this$ is a weak ref */
27
28     inline explicit JObject(jobject obj)
29     {
30         if (obj)
31         {
32             id = env->id(obj);
33             this$ = env->newGlobalRef(obj, id);
34         }
35         else
36         {
37             id = 0;
38             this$ = NULL;
39         }
40     }
41
42     inline JObject(const JObject& obj)
43     {
44         id = obj.id ? obj.id : env->id(obj.this$);
45         this$ = env->newGlobalRef(obj.this$, id);
46     }
47
48     virtual ~JObject()
49     {
50         this$ = env->deleteGlobalRef(this$, id);
51     }
52
53     JObject& weaken$()
54     {
55         if (id)
56         {
57             jobject ref = env->newGlobalRef(this$, 0);
58
59             env->deleteGlobalRef(this$, id);
60             id = 0;
61             this$ = ref;
62         }
63
64         return *this;
65     }
66
67     inline int operator!() const
68     {
69         return env->isSame(this$, NULL);
70     }
71
72     inline int operator==(const JObject& obj) const
73     {
74         return env->isSame(this$, obj.this$);
75     }
76
77     JObject& operator=(const JObject& obj)
78     {
79         jobject prev = this$;
80         int objid = obj.id ? obj.id : env->id(obj.this$);
81
82         this$ = env->newGlobalRef(obj.this$, objid);
83         env->deleteGlobalRef(prev, id);
84         id = objid;
85
86         return *this;
87     }
88 };
89
90
91 #ifdef PYTHON
92
93 #include <Python.h>
94 #include "macros.h"
95
96 class t_JObject {
97 public:
98     PyObject_HEAD
99     JObject object;
100 };
101
102 extern PyTypeObject PY_TYPE(JObject);
103
104 #endif /* PYTHON */
105
106
107 #endif /* _JObject_H */