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