Debian Codegraph @

src/main/c/jpy_jtype.c

raw symbols SCIP
1 /*
2 * Copyright 2015 Brockmann Consult GmbH
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 * This file was modified by Deephaven Data Labs.
17 *
18 */
19
20 #include "jpy_module.h"
21 #include "jpy_diag.h"
22 #include "jpy_jtype.h"
23 #include "jpy_jfield.h"
24 #include "jpy_jmethod.h"
25 #include "jpy_jobj.h"
26 #include "jpy_jbyte_buffer.h"
27 #include "jpy_conv.h"
28 #include "jpy_compat.h"
29
30 #ifdef Py_GIL_DISABLED
31 // Reentrant lock for the recursive JType_GetType() and JType_ResolveType() in free-threaded environments
32 // Note that in order to avoid a fatal circular reference issues, JType_InitSuperType() no longer tries to resolve
33 // the super types. This means it is impossible for a thread to hold a get_type lock while trying to acquire the
34 // resolve_type lock but it can still hold a resolve_type lock while trying to acquire the get_type lock. This allows
35 // maximum concurrency but also avoids deadlocks at the same time.
36 typedef struct {
37 PyMutex lock;
38 PyThreadState* owner;
39 int recursion_level;
40 } ReentrantLock;
41
42 static void acquire_lock(ReentrantLock* rlock) {
43 PyThreadState* current_thread = PyThreadState_Get();
44
45 if (rlock->owner == current_thread) {
46 rlock->recursion_level++;
47 return;
48 }
49
50 PyMutex_Lock(&(rlock->lock));
51
52 rlock->owner = current_thread;
53 rlock->recursion_level = 1;
54 }
55
56 static void release_lock(ReentrantLock* rlock) {
57 if (rlock->owner != PyThreadState_Get()) {
58 PyErr_SetString(PyExc_RuntimeError, "Lock not owned by current thread");
59 return;
60 }
61
62 rlock->recursion_level--;
63 if (rlock->recursion_level == 0) {
64 rlock->owner = NULL;
65 PyMutex_Unlock(&(rlock->lock));
66 }
67 }
68
69 static ReentrantLock get_type_rlock = {{0}, NULL, 0};
70 static ReentrantLock resolve_type_rlock = {{0}, NULL, 0};
71
72 #define ACQUIRE_GET_TYPE_LOCK() acquire_lock(&get_type_rlock)
73 #define RELEASE_GET_TYPE_LOCK() release_lock(&get_type_rlock)
74 #define ACQUIRE_RESOLVE_TYPE_LOCK() acquire_lock(&resolve_type_rlock)
75 #define RELEASE_RESOLVE_TYPE_LOCK() release_lock(&resolve_type_rlock)
76
77 #else
78 #define ACQUIRE_GET_TYPE_LOCK()
79 #define RELEASE_GET_TYPE_LOCK()
80 #define ACQUIRE_RESOLVE_TYPE_LOCK()
81 #define RELEASE_RESOLVE_TYPE_LOCK()
82 #endif
83
84 JPy_JType* JType_New(JNIEnv* jenv, jclass classRef, jboolean resolve);
85 int JType_ResolveType(JNIEnv* jenv, JPy_JType* type);
86 int JType_InitComponentType(JNIEnv* jenv, JPy_JType* type, jboolean resolve);
87 int JType_InitSuperType(JNIEnv* jenv, JPy_JType* type, jboolean resolve);
88 int JType_ProcessClassConstructors(JNIEnv* jenv, JPy_JType* type);
89 int JType_ProcessClassFields(JNIEnv* jenv, JPy_JType* type);
90 int JType_ProcessClassMethods(JNIEnv* jenv, JPy_JType* type);
91 int JType_AddMethod(JPy_JType* type, JPy_JMethod* method);
92 JPy_ReturnDescriptor* JType_CreateReturnDescriptor(JNIEnv* jenv, jclass returnType);
93 JPy_ParamDescriptor* JType_CreateParamDescriptors(JNIEnv* jenv, int paramCount, jarray paramTypes);
94 void JType_InitParamDescriptorFunctions(JPy_ParamDescriptor* paramDescriptor, jboolean isLastVarArg);
95 void JType_InitMethodParamDescriptorFunctions(JPy_JType* type, JPy_JMethod* method);
96 int JType_ProcessField(JNIEnv* jenv, JPy_JType* declaringType, PyObject* fieldKey, const char* fieldName, jclass fieldClassRef, jboolean isStatic, jboolean isFinal, jfieldID fid);
97 void JType_DisposeLocalObjectRefArg(JNIEnv* jenv, jvalue* value, void* data);
98 void JType_DisposeReadOnlyBufferArg(JNIEnv* jenv, jvalue* value, void* data);
99 void JType_DisposeWritableBufferArg(JNIEnv* jenv, jvalue* value, void* data);
100
101
102 static int JType_MatchVarArgPyArgAsFPType(const JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx,
103 struct JPy_JType *expectedType, int floatMatch);
104
105 static int JType_MatchVarArgPyArgIntType(const JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx,
106 struct JPy_JType *expectedComponentType);
107
108
109
110 JPy_JType* JType_GetTypeForObject(JNIEnv* jenv, jobject objectRef, jboolean resolve)
111 {
112 JPy_JType* type;
113 jclass classRef;
114 classRef = (*jenv)->GetObjectClass(jenv, objectRef);
115 type = JType_GetType(jenv, classRef, resolve);
116 JPy_DELETE_LOCAL_REF(classRef);
117 return type;
118 }
119
120
121 JPy_JType* JType_GetTypeForName(JNIEnv* jenv, const char* typeName, jboolean resolve)
122 {
123 const char* resourceName;
124 jclass classRef;
125 JPy_JType *result;
126
127 JPy_JType* javaType = NULL;
128 if (strcmp(typeName, "boolean") == 0) {
129 javaType = JPy_JBoolean;
130 } else if (strcmp(typeName, "char") == 0) {
131 javaType = JPy_JChar;
132 } else if (strcmp(typeName, "byte") == 0) {
133 javaType = JPy_JByte;
134 } else if (strcmp(typeName, "short") == 0) {
135 javaType = JPy_JShort;
136 } else if (strcmp(typeName, "int") == 0) {
137 javaType = JPy_JInt;
138 } else if (strcmp(typeName, "long") == 0) {
139 javaType = JPy_JLong;
140 } else if (strcmp(typeName, "float") == 0) {
141 javaType = JPy_JFloat;
142 } else if (strcmp(typeName, "double") == 0) {
143 javaType = JPy_JDouble;
144 } else if (strcmp(typeName, "void") == 0) {
145 javaType = JPy_JVoid;
146 }
147
148 if (javaType != NULL) {
149 JPy_INCREF(javaType);
150 return javaType;
151 }
152
153 if (strchr(typeName, '.') != NULL) {
154 // resourceName: Replace dots '.' by slashes '/'
155 char* c;
156 resourceName = PyMem_New(char, strlen(typeName) + 1);
157 if (resourceName == NULL) {
158 PyErr_NoMemory();
159 return NULL;
160 }
161 strcpy((char*) resourceName, typeName);
162 c = (char*) resourceName;
163 while ((c = strchr(c, '.')) != NULL) {
164 *c = '/';
165 }
166 } else {
167 resourceName = typeName;
168 }
169
170 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_GetTypeForName: typeName='%s', resourceName='%s'\n", typeName, resourceName);
171
172 classRef = (*jenv)->FindClass(jenv, resourceName);
173
174 if (typeName != resourceName) {
175 PyMem_Del((char*) resourceName);
176 }
177
178 if (classRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
179 (*jenv)->ExceptionClear(jenv);
180 PyErr_Format(PyExc_ValueError, "Java class '%s' not found", typeName);
181 return NULL;
182 }
183
184 result = JType_GetType(jenv, classRef, resolve);
185 JPy_DELETE_LOCAL_REF(classRef);
186 return result;
187 }
188
189 /**
190 * Returns a new reference.
191 */
192 JPy_JType* JType_GetType(JNIEnv* jenv, jclass classRef, jboolean resolve)
193 {
194 PyObject* typeKey;
195 PyObject* typeValue;
196 JPy_JType* type;
197 jboolean found;
198
199 if (JPy_Types == NULL) {
200 PyErr_SetString(PyExc_RuntimeError, "jpy internal error: module 'jpy' not initialized");
201 return NULL;
202 }
203
204 typeKey = JPy_FromTypeName(jenv, classRef);
205 if (typeKey == NULL) {
206 return NULL;
207 }
208
209 ACQUIRE_GET_TYPE_LOCK();
210 // borrowed ref, no need to replace with PyDict_GetItemRef because it is protected by the lock
211 typeValue = PyDict_GetItem(JPy_Types, typeKey);
212 if (typeValue == NULL) {
213
214 found = JNI_FALSE;
215
216 // Create a new type instance, the refcount is set to 1 if this call succeeds
217 type = JType_New(jenv, classRef, resolve);
218 if (type == NULL) {
219 JPy_DECREF(typeKey);
220 RELEASE_GET_TYPE_LOCK();
221 return NULL;
222 }
223
224 //printf("T1: type->tp_init=%p\n", ((PyTypeObject*)type)->tp_init);
225
226 // In order to avoid infinite recursion, we have to register the new (but yet incomplete) type first...
227 // it will increment the refcount of type
228 PyDict_SetItem(JPy_Types, typeKey, (PyObject*) type);
229
230 //printf("T2: type->tp_init=%p\n", ((PyTypeObject*)type)->tp_init);
231
232 // ... before we can continue processing the super type ...
233 // Note, at this point, the Python type has been registered-but-yet-finalized (as done in JType_InitSlots).
234 // We need to delay resolving the super classes to when they are actually referenced, so that in a cyclic
235 // reference scenario, the super classes can still be finalized (reference-able by child classes), but NOT RESOLVED
236 // (its methods/fields remain absent in the type object). This is to avoid the case where its members reference some other
237 // registered-but-yet-finalized classes in the same class hierarchy, and these classes in turn have
238 // registered-but-yet-finalized super classes, causing JType_InitSlots to fail for one of them because its super
239 // class is not finalized. When this happens, the affected classes will not be properly resolved.
240 if (JType_InitSuperType(jenv, type, JNI_FALSE) < 0) {
241 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_GetType: error: JType_InitSuperType() failed for javaName=\"%s\"\n", type->javaName);
242 PyDict_DelItem(JPy_Types, typeKey);
243 JPy_DECREF(typeKey);
244 JPy_DECREF(type);
245 RELEASE_GET_TYPE_LOCK();
246 return NULL;
247 }
248
249 //printf("T3: type->tp_init=%p\n", ((PyTypeObject*)type)->tp_init);
250
251 // ... and processing the component type.
252 if (JType_InitComponentType(jenv, type, JNI_FALSE) < 0) {
253 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_GetType: error: JType_InitComponentType() failed for javaName=\"%s\"\n", type->javaName);
254 PyDict_DelItem(JPy_Types, typeKey);
255 JPy_DECREF(typeKey);
256 JPy_DECREF(type);
257 RELEASE_GET_TYPE_LOCK();
258 return NULL;
259 }
260
261 //printf("T4: type->tp_init=%p\n", ((PyTypeObject*)type)->tp_init);
262
263 // Finally we initialise the type's slots, so that our JObj instances behave pythonic.
264 if (JType_InitSlots(type) < 0) {
265 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_GetType: error: JType_InitSlots() failed for javaName=\"%s\"\n", type->javaName);
266 PyDict_DelItem(JPy_Types, typeKey);
267 JPy_DECREF(typeKey);
268 JPy_DECREF(type);
269 RELEASE_GET_TYPE_LOCK();
270 return NULL;
271 }
272
273 JType_AddClassAttribute(jenv, type);
274 // 'type' will be refcount incremented and returned as a new reference later. 'typeKey' needs to be released.
275 JPy_DECREF(typeKey);
276 JPy_DECREF(type);
277
278 //printf("T5: type->tp_init=%p\n", ((PyTypeObject*)type)->tp_init);
279
280 } else {
281 jboolean isTypeInProgress = typeValue->ob_type == &JType_Type;
282 jboolean isFinalizedType = PyType_Check(typeValue);
283
284 found = JNI_TRUE;
285
286 if (!isTypeInProgress && !isFinalizedType) {
287 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "JType_GetType: INTERNAL ERROR: illegal typeValue=%p (type '%s') for typeKey=%p (type '%s') in 'jpy.%s'\n",
288 typeValue, Py_TYPE(typeValue)->tp_name,
289 typeKey, Py_TYPE(typeKey)->tp_name,
290 JPy_MODULE_ATTR_NAME_TYPES);
291 PyErr_Format(PyExc_RuntimeError,
292 "jpy internal error: attributes in 'jpy.%s' must be of type '%s', but found a '%s'",
293 JPy_MODULE_ATTR_NAME_TYPES, JType_Type.tp_name, Py_TYPE(typeValue)->tp_name);
294 JPy_DECREF(typeKey);
295 RELEASE_GET_TYPE_LOCK();
296 return NULL;
297 }
298
299 type = (JPy_JType*) typeValue;
300 // 'type' will be refcount incremented and returned as a new reference. 'typeKey' needs to be released.
301 JPy_DECREF(typeKey);
302 }
303
304 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_GetType: javaName=\"%s\", found=%d, resolve=%d, resolved=%d, type=%p\n", type->javaName, found, resolve, type->isResolved, type);
305 RELEASE_GET_TYPE_LOCK();
306
307 if (!type->isResolved && resolve) {
308 if (JType_ResolveType(jenv, type) < 0) {
309 return NULL;
310 }
311 }
312
313 JPy_INCREF(type);
314 return type;
315 }
316
317 /**
318 * Creates a type instance of the meta type 'JType_Type'.
319 * Such type instances are used as types for Java Objects in Python.
320 */
321 JPy_JType* JType_New(JNIEnv* jenv, jclass classRef, jboolean resolve)
322 {
323 PyTypeObject* metaType;
324 JPy_JType* type;
325
326 metaType = &JType_Type;
327
328 type = (JPy_JType*) metaType->tp_alloc(metaType, 0);
329 if (type == NULL) {
330 return NULL;
331 }
332
333 // printf("=============================================== JType_New: type->ob_type=%p\n", ((PyObject*)type)->ob_type);
334
335 type->classRef = NULL;
336 type->isResolved = JNI_FALSE;
337 type->isResolving = JNI_FALSE;
338
339 type->javaName = JPy_GetTypeName(jenv, classRef);
340 if (type->javaName == NULL) {
341 metaType->tp_free(type);
342 return NULL;
343 }
344 // The object type's name. Note that the reference is borrowed from type->javaName.
345 type->typeObj.tp_name = type->javaName;
346 // tp_init is used to identify objects instances of type jpy.JType. Make sure it is initially NULL.
347 type->typeObj.tp_init = NULL;
348
349 type->classRef = (*jenv)->NewGlobalRef(jenv, classRef);
350 if (type->classRef == NULL) {
351 PyMem_Del(type->javaName);
352 type->javaName = NULL;
353 metaType->tp_free(type);
354 PyErr_NoMemory();
355 return NULL;
356 }
357
358 type->isPrimitive = (*jenv)->CallBooleanMethod(jenv, type->classRef, JPy_Class_IsPrimitive_MID);
359 if ((*jenv)->ExceptionCheck(jenv)) {
360 (*jenv)->ExceptionClear(jenv);
361 PyMem_Del(type->javaName);
362 type->javaName = NULL;
363 metaType->tp_free(type);
364 return NULL;
365 }
366 type->isInterface = (*jenv)->CallBooleanMethod(jenv, type->classRef, JPy_Class_IsInterface_MID);
367 if ((*jenv)->ExceptionCheck(jenv)) {
368 (*jenv)->ExceptionClear(jenv);
369 PyMem_Del(type->javaName);
370 type->javaName = NULL;
371 metaType->tp_free(type);
372 return NULL;
373 }
374
375 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_New: javaName=\"%s\", resolve=%d, type=%p\n", type->javaName, resolve, type);
376
377 return type;
378 }
379
380 PyObject* JType_ConvertJavaToPythonObject(JNIEnv* jenv, JPy_JType* type, jobject objectRef)
381 {
382 if (objectRef == NULL) {
383 return JPy_FROM_JNULL();
384 }
385
386 if (type->componentType == NULL) {
387 // Scalar type, not an array, try to convert to Python equivalent
388 if (type == JPy_JBooleanObj || type == JPy_JBoolean) {
389 jboolean value = (*jenv)->CallBooleanMethod(jenv, objectRef, JPy_Boolean_BooleanValue_MID);
390 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
391 return JPy_FROM_JBOOLEAN(value);
392 } else if (type == JPy_JCharacterObj || type == JPy_JChar) {
393 jchar value = (*jenv)->CallCharMethod(jenv, objectRef, JPy_Character_CharValue_MID);
394 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
395 return JPy_FROM_JCHAR(value);
396 } else if (type == JPy_JByteObj || type == JPy_JShortObj || type == JPy_JIntegerObj || type == JPy_JShort || type == JPy_JInt) {
397 jint value = (*jenv)->CallIntMethod(jenv, objectRef, JPy_Number_IntValue_MID);
398 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
399 return JPy_FROM_JINT(value);
400 } else if (type == JPy_JLongObj || type == JPy_JLong) {
401 jlong value = (*jenv)->CallLongMethod(jenv, objectRef, JPy_Number_LongValue_MID);
402 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
403 return JPy_FROM_JLONG(value);
404 } else if (type == JPy_JFloatObj || type == JPy_JDoubleObj || type == JPy_JFloat || type == JPy_JDouble) {
405 jdouble value = (*jenv)->CallDoubleMethod(jenv, objectRef, JPy_Number_DoubleValue_MID);
406 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
407 return JPy_FROM_JDOUBLE(value);
408 } else if (type == JPy_JPyObject || type == JPy_JPyModule) {
409 jlong value = (*jenv)->CallLongMethod(jenv, objectRef, JPy_PyObject_GetPointer_MID);
410 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
411 PyObject* pyObj = (PyObject*) value;
412 JPy_INCREF(pyObj);
413 return pyObj;
414 } else if (type == JPy_JString) {
415 return JPy_FromJString(jenv, objectRef);
416 } else if (type == JPy_JObject) {
417 type = JType_GetTypeForObject(jenv, objectRef, JNI_FALSE);
418 if (type != JPy_JObject) {
419 return JType_ConvertJavaToPythonObject(jenv, type, objectRef);
420 }
421 } else if (JPy_JPyObject != NULL) {
422 // Note: JPy_JPyObject == NULL means that org.jpy.PyObject has not been loaded from the
423 // java classpath, which is OK. This is common when using jpy from Python.
424 // If org.jpy.PyObject has not been loaded, we know the object isn't a proxy.
425
426 // If this object was created by PyObject#createProxy, let's unwrap it and get back original PyObject.
427 jobject jPyObject = (*jenv)->CallStaticObjectMethod(jenv, JPy_JPyObject->classRef, JPy_PyObject_UnwrapProxy_SMID, objectRef);
428 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
429 if (jPyObject != NULL) {
430 // We know that jPyObject is of the proper type, no need to check it.
431 jlong value = (*jenv)->CallLongMethod(jenv, jPyObject, JPy_PyObject_GetPointer_MID);
432 JPy_DELETE_LOCAL_REF(jPyObject);
433 JPy_ON_JAVA_EXCEPTION_RETURN(NULL);
434 PyObject* pyObj = (PyObject*) value;
435 JPy_INCREF(pyObj);
436 return pyObj;
437 }
438 }
439 }
440
441 // For all other types than the ones handled above (namely primitive types, PyObject+PyModule, and String),
442 // we create a Java object wrapper
443 return (PyObject*) JObj_FromType(jenv, type, objectRef);
444
445 // Tried the following in order to return objects that have the actual type instead of the declared return type.
446 // Problem occurs if Java collections are used: These return java.lang.Object items and must be explicitly
447 // cast to the desired type in Python using jpy.cast(obj, type).
448 // Anyway, JObj_New() is 2x slower than JObj_FromType() and it may require definition of Java type wrappers for
449 // actually private implementation classes. For example: A java.util.List is filled with java.nio.file.Path objects,
450 // but List.get() returns a java.lang.Object. Returning the actual type is platform dependent. E.g. on
451 // Windows, it returns an instance of the internal sun.nio.fs.WindowsPath class.
452 //
453 //return (PyObject*) JObj_New(jenv, objectRef);
454 }
455
456 int JType_PythonToJavaConversionError(JPy_JType* type, PyObject* pyArg)
457 {
458 PyErr_Format(PyExc_ValueError, "cannot convert a Python '%s' to a Java '%s'", Py_TYPE(pyArg)->tp_name, type->javaName);
459 return -1;
460 }
461
462 int JType_CreateJavaObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jclass classRef, jmethodID initMID, jvalue value, jobject* objectRef)
463 {
464 Py_BEGIN_ALLOW_THREADS;
465 *objectRef = (*jenv)->NewObjectA(jenv, classRef, initMID, &value);
466 Py_END_ALLOW_THREADS;
467 if (*objectRef == NULL) {
468 PyErr_NoMemory();
469 return -1;
470 }
471 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
472 return 0;
473 }
474
475 int JType_CreateJavaObject_2(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jclass classRef, jmethodID initMID, jvalue value1, jvalue value2, jobject* objectRef)
476 {
477 Py_BEGIN_ALLOW_THREADS;
478 *objectRef = (*jenv)->NewObject(jenv, classRef, initMID, value1, value2);
479 Py_END_ALLOW_THREADS;
480 if (*objectRef == NULL) {
481 PyErr_NoMemory();
482 return -1;
483 }
484 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
485 return 0;
486 }
487
488 #define JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(TARGET_TYPE, STATIC_METHOD_ID, ARG, JOBJECT_PTR) \
489 Py_BEGIN_ALLOW_THREADS; \
490 *JOBJECT_PTR = (*jenv)->CallStaticObjectMethod(jenv, TARGET_TYPE, STATIC_METHOD_ID, ARG); \
491 Py_END_ALLOW_THREADS; \
492 if (*objectRef == NULL) { \
493 PyErr_NoMemory(); \
494 return -1; \
495 } \
496 JPy_ON_JAVA_EXCEPTION_RETURN(-1); \
497 return 0;
498
499 int JType_CreateJavaBooleanObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
500 {
501 jboolean value;
502 value = JPy_AS_JBOOLEAN(pyArg);
503 if ((signed char)value == -1) {
504 return JType_PythonToJavaConversionError(type, pyArg);
505 }
506 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Boolean_JClass, JPy_Boolean_ValueOf_SMID, value, objectRef);
507 }
508
509 int JType_CreateJavaCharacterObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
510 {
511 jchar value;
512 if (JPy_IS_CLONG(pyArg)) {
513 value = JPy_AS_JCHAR(pyArg);
514 } else {
515 return JType_PythonToJavaConversionError(type, pyArg);
516 }
517 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Character_JClass, JPy_Character_ValueOf_SMID, value, objectRef);
518 }
519
520 int JType_CreateJavaByteObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
521 {
522 jbyte value;
523 if (JPy_IS_CLONG(pyArg)) {
524 value = JPy_AS_JBYTE(pyArg);
525 } else {
526 return JType_PythonToJavaConversionError(type, pyArg);
527 }
528 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Byte_JClass, JPy_Byte_ValueOf_SMID, value, objectRef);
529 }
530
531 int JType_CreateJavaShortObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
532 {
533 jshort value;
534 if (JPy_IS_CLONG(pyArg)) {
535 value = JPy_AS_JSHORT(pyArg);
536 } else {
537 return JType_PythonToJavaConversionError(type, pyArg);
538 }
539 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Short_JClass, JPy_Short_ValueOf_SMID, value, objectRef);
540 }
541
542 int JType_CreateJavaNumberFromPythonInt(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
543 {
544 signed char b;
545 short s;
546 long i;
547 long long j;
548 j = JPy_AS_JLONG(pyArg);
549 i = (int) j;
550 s = (short) j;
551 b = (signed char) j;
552
553 if (i != j) {
554 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Long_JClass, JPy_Long_ValueOf_SMID, j, objectRef);
555 }
556 if (s != i) {
557 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Integer_JClass, JPy_Integer_ValueOf_SMID, i, objectRef);
558 }
559 if (b != s) {
560 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Short_JClass, JPy_Short_ValueOf_SMID, s, objectRef);
561 }
562 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Byte_JClass, JPy_Byte_ValueOf_SMID, b, objectRef);
563 }
564
565 int JType_CreateJavaIntegerObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
566 {
567 jint value;
568 if (JPy_IS_CLONG(pyArg)) {
569 value = JPy_AS_JINT(pyArg);
570 } else {
571 return JType_PythonToJavaConversionError(type, pyArg);
572 }
573 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Integer_JClass, JPy_Integer_ValueOf_SMID, value, objectRef);
574 }
575
576 int JType_CreateJavaLongObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
577 {
578 jlong value;
579 if (JPy_IS_CLONG(pyArg)) {
580 value = JPy_AS_JLONG(pyArg);
581 } else {
582 return JType_PythonToJavaConversionError(type, pyArg);
583 }
584 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Long_JClass, JPy_Long_ValueOf_SMID, value, objectRef);
585 }
586
587 int JType_CreateJavaFloatObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
588 {
589 jfloat value;
590 if (JPy_IS_CLONG(pyArg)) {
591 value = (jfloat) JPy_AS_JLONG(pyArg);
592 } else if (PyFloat_Check(pyArg)) {
593 value = JPy_AS_JFLOAT(pyArg);
594 } else {
595 return JType_PythonToJavaConversionError(type, pyArg);
596 }
597 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Float_JClass, JPy_Float_ValueOf_SMID, value, objectRef);
598 }
599
600 int JType_CreateJavaDoubleObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
601 {
602 jdouble value;
603 if (JPy_IS_CLONG(pyArg)) {
604 value = (jdouble) JPy_AS_JLONG(pyArg);
605 } else if (PyFloat_Check(pyArg)) {
606 value = JPy_AS_JDOUBLE(pyArg);
607 } else {
608 return JType_PythonToJavaConversionError(type, pyArg);
609 }
610 JType_CALL_STATIC_OBJECT_METHOD_1_AND_RETURN(JPy_Double_JClass, JPy_Double_ValueOf_SMID, value, objectRef);
611 }
612
613 int JType_CreateJavaPyObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef)
614 {
615 jvalue value1;
616 jvalue value2;
617
618 value1.j = (jlong) pyArg;
619 value2.z = JNI_TRUE;
620
621 JPy_INCREF(pyArg);
622 return JType_CreateJavaObject_2(jenv, type, pyArg, type->classRef, JPy_PyObject_Init_MID, value1, value2, objectRef);
623 }
624
625 int JType_CreateJavaArray(JNIEnv* jenv, JPy_JType* componentType, PyObject* pyArg, jobject* objectRef, jboolean allowObjectWrapping)
626 {
627 jint itemCount;
628 jarray arrayRef;
629 jint index;
630 PyObject* pyItem;
631
632 if (pyArg == Py_None) {
633 itemCount = 0;
634 } else if (PySequence_Check(pyArg)) {
635 itemCount = PySequence_Length(pyArg);
636 if (itemCount < 0) {
637 return -1;
638 }
639 } else {
640 PyErr_Format(PyExc_ValueError, "cannot convert a Python '%s' to a Java array of type '%s'", Py_TYPE(pyArg)->tp_name, componentType->javaName);
641 return -1;
642 }
643
644 arrayRef = NULL;
645
646 if (componentType == JPy_JBoolean) {
647 arrayRef = (*jenv)->NewBooleanArray(jenv, itemCount);
648 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
649 JPy_HandleJavaException(jenv);
650 return -1;
651 }
652 if (itemCount > 0) {
653 jboolean* items = (*jenv)->GetBooleanArrayElements(jenv, arrayRef, NULL);
654 if (items == NULL) {
655 JPy_DELETE_LOCAL_REF(arrayRef);
656 PyErr_NoMemory();
657 return -1;
658 }
659 for (index = 0; index < itemCount; index++) {
660 pyItem = PySequence_GetItem(pyArg, index);
661 if (pyItem == NULL) {
662 (*jenv)->ReleaseBooleanArrayElements(jenv, arrayRef, items, 0);
663 JPy_DELETE_LOCAL_REF(arrayRef);
664 return -1;
665 }
666 items[index] = JPy_AS_JBOOLEAN(pyItem);
667 JPy_DECREF(pyItem);
668 if (PyErr_Occurred()) {
669 (*jenv)->ReleaseBooleanArrayElements(jenv, arrayRef, items, 0);
670 JPy_DELETE_LOCAL_REF(arrayRef);
671 return -1;
672 }
673 }
674 (*jenv)->ReleaseBooleanArrayElements(jenv, arrayRef, items, 0);
675 }
676 } else if (componentType == JPy_JByte) {
677 arrayRef = (*jenv)->NewByteArray(jenv, itemCount);
678 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
679 JPy_HandleJavaException(jenv);
680 return -1;
681 }
682 if (itemCount > 0) {
683 jbyte* items = (*jenv)->GetByteArrayElements(jenv, arrayRef, NULL);
684 if (items == NULL) {
685 JPy_DELETE_LOCAL_REF(arrayRef);
686 PyErr_NoMemory();
687 return -1;
688 }
689 for (index = 0; index < itemCount; index++) {
690 pyItem = PySequence_GetItem(pyArg, index);
691 if (pyItem == NULL) {
692 (*jenv)->ReleaseByteArrayElements(jenv, arrayRef, items, 0);
693 JPy_DELETE_LOCAL_REF(arrayRef);
694 return -1;
695 }
696 items[index] = JPy_AS_JBYTE(pyItem);
697 JPy_DECREF(pyItem);
698 if (PyErr_Occurred()) {
699 (*jenv)->ReleaseByteArrayElements(jenv, arrayRef, items, 0);
700 JPy_DELETE_LOCAL_REF(arrayRef);
701 return -1;
702 }
703 }
704 (*jenv)->ReleaseByteArrayElements(jenv, arrayRef, items, 0);
705 }
706 } else if (componentType == JPy_JChar) {
707 arrayRef = (*jenv)->NewCharArray(jenv, itemCount);
708 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
709 JPy_HandleJavaException(jenv);
710 return -1;
711 }
712 if (itemCount > 0) {
713 jchar* items = (*jenv)->GetCharArrayElements(jenv, arrayRef, NULL);
714 if (items == NULL) {
715 JPy_DELETE_LOCAL_REF(arrayRef);
716 PyErr_NoMemory();
717 return -1;
718 }
719 for (index = 0; index < itemCount; index++) {
720 pyItem = PySequence_GetItem(pyArg, index);
721 if (pyItem == NULL) {
722 (*jenv)->ReleaseCharArrayElements(jenv, arrayRef, items, 0);
723 JPy_DELETE_LOCAL_REF(arrayRef);
724 return -1;
725 }
726 items[index] = JPy_AS_JCHAR(pyItem);
727 JPy_DECREF(pyItem);
728 if (PyErr_Occurred()) {
729 (*jenv)->ReleaseCharArrayElements(jenv, arrayRef, items, 0);
730 JPy_DELETE_LOCAL_REF(arrayRef);
731 return -1;
732 }
733 }
734 (*jenv)->ReleaseCharArrayElements(jenv, arrayRef, items, 0);
735 }
736 } else if (componentType == JPy_JShort) {
737 arrayRef = (*jenv)->NewShortArray(jenv, itemCount);
738 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
739 JPy_HandleJavaException(jenv);
740 return -1;
741 }
742 if (itemCount > 0) {
743 jshort* items = (*jenv)->GetShortArrayElements(jenv, arrayRef, NULL);
744 if (items == NULL) {
745 JPy_DELETE_LOCAL_REF(arrayRef);
746 PyErr_NoMemory();
747 return -1;
748 }
749 for (index = 0; index < itemCount; index++) {
750 pyItem = PySequence_GetItem(pyArg, index);
751 if (pyItem == NULL) {
752 (*jenv)->ReleaseShortArrayElements(jenv, arrayRef, items, 0);
753 JPy_DELETE_LOCAL_REF(arrayRef);
754 return -1;
755 }
756 items[index] = JPy_AS_JSHORT(pyItem);
757 JPy_DECREF(pyItem);
758 if (PyErr_Occurred()) {
759 (*jenv)->ReleaseShortArrayElements(jenv, arrayRef, items, 0);
760 JPy_DELETE_LOCAL_REF(arrayRef);
761 return -1;
762 }
763 }
764 (*jenv)->ReleaseShortArrayElements(jenv, arrayRef, items, 0);
765 }
766 } else if (componentType == JPy_JInt) {
767 arrayRef = (*jenv)->NewIntArray(jenv, itemCount);
768 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
769 JPy_HandleJavaException(jenv);
770 return -1;
771 }
772 if (itemCount > 0) {
773 jint* items = (*jenv)->GetIntArrayElements(jenv, arrayRef, NULL);
774 if (items == NULL) {
775 JPy_DELETE_LOCAL_REF(arrayRef);
776 PyErr_NoMemory();
777 return -1;
778 }
779 for (index = 0; index < itemCount; index++) {
780 pyItem = PySequence_GetItem(pyArg, index);
781 if (pyItem == NULL) {
782 (*jenv)->ReleaseIntArrayElements(jenv, arrayRef, items, 0);
783 JPy_DELETE_LOCAL_REF(arrayRef);
784 return -1;
785 }
786 items[index] = JPy_AS_JINT(pyItem);
787 JPy_DECREF(pyItem);
788 if (PyErr_Occurred()) {
789 (*jenv)->ReleaseIntArrayElements(jenv, arrayRef, items, 0);
790 JPy_DELETE_LOCAL_REF(arrayRef);
791 return -1;
792 }
793 }
794 (*jenv)->ReleaseIntArrayElements(jenv, arrayRef, items, 0);
795 }
796 } else if (componentType == JPy_JLong) {
797 arrayRef = (*jenv)->NewLongArray(jenv, itemCount);
798 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
799 JPy_HandleJavaException(jenv);
800 return -1;
801 }
802 if (itemCount > 0) {
803 jlong* items = (*jenv)->GetLongArrayElements(jenv, arrayRef, NULL);
804 if (items == NULL) {
805 JPy_DELETE_LOCAL_REF(arrayRef);
806 PyErr_NoMemory();
807 return -1;
808 }
809 for (index = 0; index < itemCount; index++) {
810 pyItem = PySequence_GetItem(pyArg, index);
811 if (pyItem == NULL) {
812 (*jenv)->ReleaseLongArrayElements(jenv, arrayRef, items, 0);
813 JPy_DELETE_LOCAL_REF(arrayRef);
814 return -1;
815 }
816 items[index] = JPy_AS_JLONG(pyItem);
817 JPy_DECREF(pyItem);
818 if (PyErr_Occurred()) {
819 (*jenv)->ReleaseLongArrayElements(jenv, arrayRef, items, 0);
820 JPy_DELETE_LOCAL_REF(arrayRef);
821 return -1;
822 }
823 }
824 (*jenv)->ReleaseLongArrayElements(jenv, arrayRef, items, 0);
825 }
826 } else if (componentType == JPy_JFloat) {
827 arrayRef = (*jenv)->NewFloatArray(jenv, itemCount);
828 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
829 JPy_HandleJavaException(jenv);
830 return -1;
831 }
832 if (itemCount > 0) {
833 jfloat* items = (*jenv)->GetFloatArrayElements(jenv, arrayRef, NULL);
834 if (items == NULL) {
835 JPy_DELETE_LOCAL_REF(arrayRef);
836 PyErr_NoMemory();
837 return -1;
838 }
839 for (index = 0; index < itemCount; index++) {
840 pyItem = PySequence_GetItem(pyArg, index);
841 if (pyItem == NULL) {
842 (*jenv)->ReleaseFloatArrayElements(jenv, arrayRef, items, 0);
843 JPy_DELETE_LOCAL_REF(arrayRef);
844 return -1;
845 }
846 items[index] = JPy_AS_JFLOAT(pyItem);
847 JPy_DECREF(pyItem);
848 if (PyErr_Occurred()) {
849 (*jenv)->ReleaseFloatArrayElements(jenv, arrayRef, items, 0);
850 JPy_DELETE_LOCAL_REF(arrayRef);
851 return -1;
852 }
853 }
854 (*jenv)->ReleaseFloatArrayElements(jenv, arrayRef, items, 0);
855 }
856 } else if (componentType == JPy_JDouble) {
857 arrayRef = (*jenv)->NewDoubleArray(jenv, itemCount);
858 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
859 JPy_HandleJavaException(jenv);
860 return -1;
861 }
862 if (itemCount > 0) {
863 jdouble* items = (*jenv)->GetDoubleArrayElements(jenv, arrayRef, NULL);
864 if (items == NULL) {
865 JPy_DELETE_LOCAL_REF(arrayRef);
866 PyErr_NoMemory();
867 return -1;
868 }
869 for (index = 0; index < itemCount; index++) {
870 pyItem = PySequence_GetItem(pyArg, index);
871 if (pyItem == NULL) {
872 (*jenv)->ReleaseDoubleArrayElements(jenv, arrayRef, items, 0);
873 JPy_DELETE_LOCAL_REF(arrayRef);
874 return -1;
875 }
876 items[index] = JPy_AS_JDOUBLE(pyItem);
877 JPy_DECREF(pyItem);
878 if (PyErr_Occurred()) {
879 (*jenv)->ReleaseDoubleArrayElements(jenv, arrayRef, items, 0);
880 JPy_DELETE_LOCAL_REF(arrayRef);
881 return -1;
882 }
883 }
884 (*jenv)->ReleaseDoubleArrayElements(jenv, arrayRef, items, 0);
885 }
886 } else if (!componentType->isPrimitive) {
887 jobject jItem;
888 arrayRef = (*jenv)->NewObjectArray(jenv, itemCount, componentType->classRef, NULL);
889 if (arrayRef == NULL || (*jenv)->ExceptionCheck(jenv)) {
890 JPy_HandleJavaException(jenv);
891 return -1;
892 }
893 for (index = 0; index < itemCount; index++) {
894 pyItem = PySequence_GetItem(pyArg, index);
895 if (pyItem == NULL) {
896 JPy_DELETE_LOCAL_REF(arrayRef);
897 return -1;
898 }
899 if (JType_ConvertPythonToJavaObject(jenv, componentType, pyItem, &jItem, allowObjectWrapping) < 0) {
900 JPy_DELETE_LOCAL_REF(arrayRef);
901 JPy_DECREF(pyItem);
902 return -1;
903 }
904 JPy_DECREF(pyItem);
905 (*jenv)->SetObjectArrayElement(jenv, arrayRef, index, jItem);
906 if ((*jenv)->ExceptionCheck(jenv)) {
907 JPy_DELETE_LOCAL_REF(arrayRef);
908 JPy_DELETE_LOCAL_REF(jItem);
909 JPy_HandleJavaException(jenv);
910 return -1;
911 }
912 }
913 } else {
914 PyErr_Format(PyExc_ValueError, "illegal Java array component type %s", componentType->javaName);
915 return -1;
916 }
917
918 *objectRef = arrayRef;
919 return 0;
920 }
921
922 int JType_ConvertPythonToJavaObject(JNIEnv* jenv, JPy_JType* type, PyObject* pyArg, jobject* objectRef, jboolean allowObjectWrapping)
923 {
924 // Note: There may be a potential memory leak here.
925 // If a new local reference is created in this function and assigned to *objectRef, the reference may escape.
926 // If the reference is created for an argument to a JNI call, we already delete the ref (see JMethod_InvokeMethod()).
927 // In other cases we actually have to call (*jenv)->DeleteLocalRef(jenv, *objectRef) some time later.
928
929 if (pyArg == Py_None) {
930 // None converts into NULL
931 *objectRef = NULL;
932 // todo: if the return type is PyObject, we should return Py_None instead
933 return 0;
934 }
935
936 // If it is already a Java object wrapper JObj, and assignable, then we are done
937 if (JObj_Check(pyArg)) {
938 jobject jobj = ((JPy_JObj*) pyArg)->objectRef;
939 jclass jobjclass = (*jenv)->GetObjectClass(jenv, jobj);
940
941 if ((*jenv)->IsAssignableFrom(jenv, jobjclass, type->classRef)) {
942 JPy_DELETE_LOCAL_REF(jobjclass);
943
944 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_ConvertPythonToJavaObject: unwrapping JObj into type->javaName=\"%s\"\n", type->javaName);
945
946 jobj = (*jenv)->NewLocalRef(jenv, jobj); // need a new reference to it
947 *objectRef = jobj;
948 if (jobj == NULL) {
949 PyErr_NoMemory();
950 return -1;
951 }
952 return 0;
953 }
954 JPy_DELETE_LOCAL_REF(jobjclass);
955 }
956
957 // If it is already a Java type wrapper JType, and assignable, then we are done
958 if (JType_Check(pyArg)) {
959 jclass jobj = ((JPy_JType*)pyArg)->classRef;
960 jclass jobjclass = (*jenv)->GetObjectClass(jenv, jobj);
961
962 if ((*jenv)->IsAssignableFrom(jenv, jobjclass, type->classRef)) {
963 JPy_DELETE_LOCAL_REF(jobjclass);
964
965 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_ConvertPythonToJavaObject: unwrapping JType into type->javaName=\"%s\"\n", type->javaName);
966
967 jobj = (*jenv)->NewLocalRef(jenv, jobj); // need a new reference to it
968 *objectRef = jobj;
969 if (jobj == NULL) {
970 PyErr_NoMemory();
971 return -1;
972 }
973 return 0;
974 }
975 JPy_DELETE_LOCAL_REF(jobjclass);
976 }
977
978 if (type->componentType != NULL) {
979 // For any other Python argument create a Java object (a new local reference)
980 return JType_CreateJavaArray(jenv, type->componentType, pyArg, objectRef, allowObjectWrapping);
981 } else if (type == JPy_JBoolean || type == JPy_JBooleanObj) {
982 return JType_CreateJavaBooleanObject(jenv, type, pyArg, objectRef);
983 } else if (type == JPy_JChar || type == JPy_JCharacterObj) {
984 return JType_CreateJavaCharacterObject(jenv, type, pyArg, objectRef);
985 } else if (type == JPy_JByte || type == JPy_JByteObj) {
986 return JType_CreateJavaByteObject(jenv, type, pyArg, objectRef);
987 } else if (type == JPy_JShort || type == JPy_JShortObj) {
988 return JType_CreateJavaShortObject(jenv, type, pyArg, objectRef);
989 } else if (type == JPy_JInt || type == JPy_JIntegerObj) {
990 return JType_CreateJavaIntegerObject(jenv, type, pyArg, objectRef);
991 } else if (type == JPy_JLong || type == JPy_JLongObj) {
992 return JType_CreateJavaLongObject(jenv, type, pyArg, objectRef);
993 } else if (type == JPy_JFloat || type == JPy_JFloatObj) {
994 return JType_CreateJavaFloatObject(jenv, type, pyArg, objectRef);
995 } else if (type == JPy_JDouble || type == JPy_JDoubleObj) {
996 return JType_CreateJavaDoubleObject(jenv, type, pyArg, objectRef);
997 } else if (type == JPy_JPyObject) {
998 return JType_CreateJavaPyObject(jenv, type, pyArg, objectRef);
999 } else if (JPy_IS_STR(pyArg) && (type == JPy_JString || type == JPy_JObject || (*jenv)->IsAssignableFrom(jenv, JPy_JString->classRef, type->classRef))) {
1000 return JPy_AsJString(jenv, pyArg, objectRef);
1001 } else if (PyBool_Check(pyArg) && (type == JPy_JObject || (*jenv)->IsAssignableFrom(jenv, JPy_Boolean_JClass, type->classRef))) {
1002 return JType_CreateJavaBooleanObject(jenv, type, pyArg, objectRef);
1003 } else if (JPy_IS_CLONG(pyArg) && (type == JPy_JObject || (*jenv)->IsAssignableFrom(jenv, JPy_Number_JClass, type->classRef))) {
1004 return JType_CreateJavaNumberFromPythonInt(jenv, type, pyArg, objectRef);
1005 } else if (JPy_IS_CLONG(pyArg) && ((*jenv)->IsAssignableFrom(jenv, JPy_Integer_JClass, type->classRef))) {
1006 return JType_CreateJavaIntegerObject(jenv, type, pyArg, objectRef);
1007 } else if (JPy_IS_CLONG(pyArg) && (*jenv)->IsAssignableFrom(jenv, JPy_Long_JClass, type->classRef)) {
1008 return JType_CreateJavaLongObject(jenv, type, pyArg, objectRef);
1009 } else if (PyFloat_Check(pyArg) && (type == JPy_JObject || (*jenv)->IsAssignableFrom(jenv, JPy_Double_JClass, type->classRef))) {
1010 return JType_CreateJavaDoubleObject(jenv, type, pyArg, objectRef);
1011 } else if (PyFloat_Check(pyArg) && (*jenv)->IsAssignableFrom(jenv, JPy_Float_JClass, type->classRef)) {
1012 return JType_CreateJavaFloatObject(jenv, type, pyArg, objectRef);
1013 } else if (type == JPy_JObject && allowObjectWrapping) {
1014 return JType_CreateJavaPyObject(jenv, JPy_JPyObject, pyArg, objectRef);
1015 }
1016 return JType_PythonToJavaConversionError(type, pyArg);
1017 }
1018
1019
1020 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1021 // The following functions deal with type creation, initialisation, and resolution.
1022
1023
1024 /**
1025 * Fill the type __dict__ with our Java class constructors and methods.
1026 * Constructors will be available using the key named __jinit__.
1027 * Methods will be available using their method name.
1028 */
1029 int JType_ResolveType(JNIEnv* jenv, JPy_JType* type)
1030 {
1031 PyTypeObject* typeObj;
1032
1033 ACQUIRE_RESOLVE_TYPE_LOCK();
1034
1035 if (type->isResolved || type->isResolving) {
1036 RELEASE_RESOLVE_TYPE_LOCK();
1037 return 0;
1038 }
1039
1040 type->isResolving = JNI_TRUE;
1041
1042 typeObj = JTYPE_AS_PYTYPE(type);
1043 if (typeObj->tp_base != NULL && JType_Check((PyObject*) typeObj->tp_base)) {
1044 JPy_JType* baseType = (JPy_JType*) typeObj->tp_base;
1045 if (!baseType->isResolved) {
1046 if (JType_ResolveType(jenv, baseType) < 0) {
1047 type->isResolving = JNI_FALSE;
1048 RELEASE_RESOLVE_TYPE_LOCK();
1049 return -1;
1050 }
1051 }
1052 }
1053
1054 //printf("JType_ResolveType 1\n");
1055 if (JType_ProcessClassConstructors(jenv, type) < 0) {
1056 type->isResolving = JNI_FALSE;
1057 RELEASE_RESOLVE_TYPE_LOCK();
1058 return -1;
1059 }
1060
1061 //printf("JType_ResolveType 2\n");
1062 if (JType_ProcessClassMethods(jenv, type) < 0) {
1063 type->isResolving = JNI_FALSE;
1064 RELEASE_RESOLVE_TYPE_LOCK();
1065 return -1;
1066 }
1067
1068 //printf("JType_ResolveType 3\n");
1069 if (JType_ProcessClassFields(jenv, type) < 0) {
1070 type->isResolving = JNI_FALSE;
1071 RELEASE_RESOLVE_TYPE_LOCK();
1072 return -1;
1073 }
1074
1075 //printf("JType_ResolveType 4\n");
1076 type->isResolving = JNI_FALSE;
1077 type->isResolved = JNI_TRUE;
1078
1079 RELEASE_RESOLVE_TYPE_LOCK();
1080 return 0;
1081 }
1082
1083 jboolean JType_AcceptMethod(JPy_JType* declaringClass, JPy_JMethod* method)
1084 {
1085 PyObject* callable;
1086 PyObject* callableResult;
1087
1088 //printf("JType_AcceptMethod: javaName='%s'\n", overloadedMethod->declaringClass->javaName);
1089 #if PY_VERSION_HEX < 0x030D0000 // < 3.13
1090 // borrowed ref
1091 callable = PyDict_GetItemString(JPy_Type_Callbacks, declaringClass->javaName);
1092 JPy_XINCREF(callable);
1093 #else
1094 // https://docs.python.org/3/howto/free-threading-extensions.html#borrowed-references
1095 // PyDict_GetItemStringRef() is a thread safe version of PyDict_GetItemString() and returns a new reference
1096 if (PyDict_GetItemStringRef(JPy_Type_Callbacks, declaringClass->javaName, &callable) != 1) {
1097 callable = NULL;
1098 }
1099 #endif
1100
1101 if (callable != NULL) {
1102 if (PyCallable_Check(callable)) {
1103 callableResult = PyObject_CallFunction(callable, "OO", declaringClass, method);
1104 if (callableResult == Py_None || callableResult == Py_False) {
1105 JPy_XDECREF(callable);
1106 return JNI_FALSE;
1107 } else if (callableResult == NULL) {
1108 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_AcceptMethod: warning: failed to invoke callback on method addition\n");
1109 // Ignore this problem and continue
1110 }
1111 }
1112 }
1113 JPy_XDECREF(callable);
1114
1115 return JNI_TRUE;
1116 }
1117
1118
1119 int JType_ProcessMethod(JNIEnv* jenv, JPy_JType* type, PyObject* methodKey, const char* methodName, jclass returnType, jarray paramTypes, jboolean isStatic, jboolean isVarArgs, jmethodID mid)
1120 {
1121 JPy_ParamDescriptor* paramDescriptors = NULL;
1122 JPy_ReturnDescriptor* returnDescriptor = NULL;
1123 jint paramCount;
1124 JPy_JMethod* method;
1125
1126 paramCount = (*jenv)->GetArrayLength(jenv, paramTypes);
1127 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_ProcessMethod: methodName=\"%s\", paramCount=%d, isStatic=%d, isVarArgs=%d, mid=%p\n", methodName, paramCount, isStatic, isVarArgs, mid);
1128
1129 if (paramCount > 0) {
1130 paramDescriptors = JType_CreateParamDescriptors(jenv, paramCount, paramTypes);
1131 if (paramDescriptors == NULL) {
1132 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE + JPy_DIAG_F_ERR, "JType_ProcessMethod: WARNING: Java method '%s' rejected because an error occurred during parameter type processing\n", methodName);
1133 return -1;
1134 }
1135 } else {
1136 paramDescriptors = NULL;
1137 }
1138
1139 if (returnType != NULL) {
1140 returnDescriptor = JType_CreateReturnDescriptor(jenv, returnType);
1141 if (returnDescriptor == NULL) {
1142 PyMem_Del(paramDescriptors);
1143 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE + JPy_DIAG_F_ERR, "JType_ProcessMethod: WARNING: Java method '%s' rejected because an error occurred during return type processing\n", methodName);
1144 return -1;
1145 }
1146 } else {
1147 returnDescriptor = NULL;
1148 }
1149
1150 method = JMethod_New(type, methodKey, paramCount, paramDescriptors, returnDescriptor, isStatic, isVarArgs, mid);
1151 if (method == NULL) {
1152 PyMem_Del(paramDescriptors);
1153 PyMem_Del(returnDescriptor);
1154 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE + JPy_DIAG_F_ERR, "JType_ProcessMethod: WARNING: Java method '%s' rejected because an error occurred during method instantiation\n", methodName);
1155 return -1;
1156 }
1157
1158 if (JType_AcceptMethod(type, method)) {
1159 JType_InitMethodParamDescriptorFunctions(type, method);
1160 JType_AddMethod(type, method);
1161 } else {
1162 JMethod_Del(method);
1163 }
1164
1165 return 0;
1166 }
1167
1168 int JType_InitComponentType(JNIEnv* jenv, JPy_JType* type, jboolean resolve)
1169 {
1170 jclass componentTypeRef;
1171
1172 componentTypeRef = (jclass) (*jenv)->CallObjectMethod(jenv, type->classRef, JPy_Class_GetComponentType_MID);
1173 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1174 if (componentTypeRef != NULL) {
1175 type->componentType = JType_GetType(jenv, componentTypeRef, resolve);
1176 JPy_DELETE_LOCAL_REF(componentTypeRef);
1177 if (type->componentType == NULL) {
1178 return -1;
1179 }
1180 } else {
1181 type->componentType = NULL;
1182 }
1183
1184 return 0;
1185 }
1186
1187 int JType_InitSuperType(JNIEnv* jenv, JPy_JType* type, jboolean resolve)
1188 {
1189 jclass superClassRef;
1190
1191 superClassRef = (*jenv)->GetSuperclass(jenv, type->classRef);
1192 if (superClassRef != NULL) {
1193 type->superType = JType_GetType(jenv, superClassRef, resolve);
1194 if (type->superType == NULL) {
1195 return -1;
1196 }
1197 JPy_DELETE_LOCAL_REF(superClassRef);
1198 } else if (type->isInterface && JPy_JObject != NULL) {
1199 // This solves the problems that java.lang.Object methods can not be called on interfaces (https://github.com/bcdev/jpy/issues/57)
1200 type->superType = JPy_JObject;
1201 JPy_INCREF(type->superType);
1202 } else {
1203 type->superType = NULL;
1204 }
1205
1206 return 0;
1207 }
1208
1209
1210 int JType_ProcessClassConstructors(JNIEnv* jenv, JPy_JType* type)
1211 {
1212 jclass classRef;
1213 jobject constructors;
1214 jobject constructor;
1215 jobject parameterTypes;
1216 jint modifiers;
1217 jint constrCount;
1218 jint i;
1219 jboolean isPublic;
1220 jboolean isVarArg;
1221 jmethodID mid;
1222 PyObject* methodKey;
1223
1224 classRef = type->classRef;
1225 methodKey = Py_BuildValue("s", JPy_JTYPE_ATTR_NAME_JINIT);
1226 constructors = (*jenv)->CallObjectMethod(jenv, classRef, JPy_Class_GetDeclaredConstructors_MID);
1227 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1228 constrCount = (*jenv)->GetArrayLength(jenv, constructors);
1229
1230 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_ProcessClassConstructors: constrCount=%d\n", constrCount);
1231
1232 for (i = 0; i < constrCount; i++) {
1233 constructor = (*jenv)->GetObjectArrayElement(jenv, constructors, i);
1234 modifiers = (*jenv)->CallIntMethod(jenv, constructor, JPy_Constructor_GetModifiers_MID);
1235 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1236 isPublic = (modifiers & 0x0001) != 0;
1237 isVarArg = (modifiers & 0x0080) != 0;
1238 if (isPublic) {
1239 parameterTypes = (*jenv)->CallObjectMethod(jenv, constructor, JPy_Constructor_GetParameterTypes_MID);
1240 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1241 mid = (*jenv)->FromReflectedMethod(jenv, constructor);
1242 JType_ProcessMethod(jenv, type, methodKey, JPy_JTYPE_ATTR_NAME_JINIT, NULL, parameterTypes, 1, isVarArg, mid);
1243 JPy_DELETE_LOCAL_REF(parameterTypes);
1244 }
1245 JPy_DELETE_LOCAL_REF(constructor);
1246 }
1247
1248 JPy_DELETE_LOCAL_REF(constructors);
1249
1250 return 0;
1251 }
1252
1253
1254 int JType_ProcessClassFields(JNIEnv* jenv, JPy_JType* type)
1255 {
1256 jclass classRef;
1257 jobject fields;
1258 jobject field;
1259 jobject fieldNameStr;
1260 jobject fieldTypeObj;
1261 jint modifiers;
1262 jint fieldCount;
1263 jint i;
1264 jboolean isStatic;
1265 jboolean isPublic;
1266 jboolean isFinal;
1267 const char * fieldName;
1268 jfieldID fid;
1269 PyObject* fieldKey;
1270
1271 classRef = type->classRef;
1272 if (type->isInterface) {
1273 fields = (*jenv)->CallObjectMethod(jenv, classRef, JPy_Class_GetFields_MID);
1274 } else {
1275 fields = (*jenv)->CallObjectMethod(jenv, classRef, JPy_Class_GetDeclaredFields_MID);
1276 }
1277 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1278 fieldCount = (*jenv)->GetArrayLength(jenv, fields);
1279
1280 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_ProcessClassFields: fieldCount=%d\n", fieldCount);
1281
1282 for (i = 0; i < fieldCount; i++) {
1283 field = (*jenv)->GetObjectArrayElement(jenv, fields, i);
1284 modifiers = (*jenv)->CallIntMethod(jenv, field, JPy_Field_GetModifiers_MID);
1285 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1286 // see http://docs.oracle.com/javase/6/docs/api/constant-values.html#java.lang.reflect.Modifier.PUBLIC
1287 isPublic = (modifiers & 0x0001) != 0;
1288 isStatic = (modifiers & 0x0008) != 0;
1289 isFinal = (modifiers & 0x0010) != 0;
1290 if (isPublic) {
1291 fieldNameStr = (*jenv)->CallObjectMethod(jenv, field, JPy_Field_GetName_MID);
1292 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1293 fieldTypeObj = (*jenv)->CallObjectMethod(jenv, field, JPy_Field_GetType_MID);
1294 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1295 fid = (*jenv)->FromReflectedField(jenv, field);
1296
1297 fieldName = (*jenv)->GetStringUTFChars(jenv, fieldNameStr, NULL);
1298 fieldKey = Py_BuildValue("s", fieldName);
1299 JType_ProcessField(jenv, type, fieldKey, fieldName, fieldTypeObj, isStatic, isFinal, fid);
1300 (*jenv)->ReleaseStringUTFChars(jenv, fieldNameStr, fieldName);
1301
1302 JPy_DELETE_LOCAL_REF(fieldTypeObj);
1303 JPy_DELETE_LOCAL_REF(fieldNameStr);
1304 }
1305 JPy_DELETE_LOCAL_REF(field);
1306 }
1307 JPy_DELETE_LOCAL_REF(fields);
1308 return 0;
1309 }
1310
1311 int JType_ProcessClassMethods(JNIEnv* jenv, JPy_JType* type) {
1312 jclass classRef;
1313 jobject methods;
1314 jobject method;
1315 jobject methodNameStr;
1316 jobject returnType;
1317 jobject parameterTypes;
1318 jint modifiers;
1319 jint methodCount;
1320 jint i;
1321 jboolean isStatic;
1322 jboolean isVarArg;
1323 jboolean isPublic;
1324 jboolean isBridge;
1325 const char *methodName;
1326 jmethodID mid;
1327 PyObject *methodKey;
1328
1329 classRef = type->classRef;
1330
1331 methods = (*jenv)->CallObjectMethod(jenv, classRef, JPy_Class_GetMethods_MID);
1332 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1333 methodCount = (*jenv)->GetArrayLength(jenv, methods);
1334 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1335
1336 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_ProcessClassMethods: methodCount=%d\n", methodCount);
1337
1338 for (i = 0; i < methodCount; i++) {
1339 method = (*jenv)->GetObjectArrayElement(jenv, methods, i);
1340 modifiers = (*jenv)->CallIntMethod(jenv, method, JPy_Method_GetModifiers_MID);
1341 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1342
1343 // see http://docs.oracle.com/javase/6/docs/api/constant-values.html#java.lang.reflect.Modifier.PUBLIC
1344 isPublic = (modifiers & 0x0001) != 0;
1345 isStatic = (modifiers & 0x0008) != 0;
1346 isVarArg = (modifiers & 0x0080) != 0;
1347 isBridge = (modifiers & 0x0040) != 0;
1348 // we exclude bridge methods; as covariant return types will result in bridge methods that cause ambiguity
1349 if (isPublic && !isBridge) {
1350 methodNameStr = (*jenv)->CallObjectMethod(jenv, method, JPy_Method_GetName_MID);
1351 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1352 returnType = (*jenv)->CallObjectMethod(jenv, method, JPy_Method_GetReturnType_MID);
1353 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1354 parameterTypes = (*jenv)->CallObjectMethod(jenv, method, JPy_Method_GetParameterTypes_MID);
1355 JPy_ON_JAVA_EXCEPTION_RETURN(-1);
1356 mid = (*jenv)->FromReflectedMethod(jenv, method);
1357
1358 methodName = (*jenv)->GetStringUTFChars(jenv, methodNameStr, NULL);
1359 methodKey = Py_BuildValue("s", methodName);
1360 JType_ProcessMethod(jenv, type, methodKey, methodName, returnType, parameterTypes, isStatic, isVarArg, mid);
1361 (*jenv)->ReleaseStringUTFChars(jenv, methodNameStr, methodName);
1362
1363 JPy_DELETE_LOCAL_REF(parameterTypes);
1364 JPy_DELETE_LOCAL_REF(returnType);
1365 JPy_DELETE_LOCAL_REF(methodNameStr);
1366 }
1367 JPy_DELETE_LOCAL_REF(method);
1368 }
1369 JPy_DELETE_LOCAL_REF(methods);
1370 return 0;
1371 }
1372
1373 jboolean JType_AcceptField(JPy_JType* declaringClass, JPy_JField* field)
1374 {
1375 return JNI_TRUE;
1376 }
1377
1378 int JType_AddField(JPy_JType* declaringClass, JPy_JField* field)
1379 {
1380 PyObject* typeDict;
1381
1382 typeDict = declaringClass->typeObj.tp_dict;
1383 if (typeDict == NULL) {
1384 PyErr_SetString(PyExc_RuntimeError, "jpy internal error: missing attribute '__dict__' in JType");
1385 return -1;
1386 }
1387
1388 PyDict_SetItem(typeDict, field->name, (PyObject*) field);
1389 return 0;
1390 }
1391
1392 int JType_AddClassAttribute(JNIEnv* jenv, JPy_JType* declaringClass)
1393 {
1394 PyObject* typeDict;
1395 if (JPy_JClass != NULL) {
1396 typeDict = declaringClass->typeObj.tp_dict;
1397 if (typeDict == NULL) {
1398 PyErr_SetString(PyExc_RuntimeError, "jpy internal error: missing attribute '__dict__' in JType");
1399 return -1;
1400 }
1401 PyDict_SetItem(typeDict, Py_BuildValue("s", "jclass"), (PyObject*) JObj_FromType(jenv, JPy_JClass, declaringClass->classRef));
1402 PyDict_SetItem(typeDict, Py_BuildValue("s", "jclassname"), (PyObject*) JPy_FROM_CSTR(declaringClass->typeObj.tp_name));
1403 }
1404 return 0;
1405 }
1406
1407 int JType_AddFieldAttribute(JNIEnv* jenv, JPy_JType* declaringClass, PyObject* fieldName, JPy_JType* fieldType, jfieldID fid)
1408 {
1409 PyObject* typeDict;
1410 PyObject* fieldValue;
1411
1412 typeDict = declaringClass->typeObj.tp_dict;
1413 if (typeDict == NULL) {
1414 PyErr_SetString(PyExc_RuntimeError, "jpy internal error: missing attribute '__dict__' in JType");
1415 return -1;
1416 }
1417
1418 if (fieldType == JPy_JBoolean) {
1419 jboolean item = (*jenv)->GetStaticBooleanField(jenv, declaringClass->classRef, fid);
1420 fieldValue = JPy_FROM_JBOOLEAN(item);
1421 } else if (fieldType == JPy_JChar) {
1422 jchar item = (*jenv)->GetStaticCharField(jenv, declaringClass->classRef, fid);
1423 fieldValue = JPy_FROM_JCHAR(item);
1424 } else if (fieldType == JPy_JByte) {
1425 jbyte item = (*jenv)->GetStaticByteField(jenv, declaringClass->classRef, fid);
1426 fieldValue = JPy_FROM_JBYTE(item);
1427 } else if (fieldType == JPy_JShort) {
1428 jshort item = (*jenv)->GetStaticShortField(jenv, declaringClass->classRef, fid);
1429 fieldValue = JPy_FROM_JSHORT(item);
1430 } else if (fieldType == JPy_JInt) {
1431 jint item = (*jenv)->GetStaticIntField(jenv, declaringClass->classRef, fid);
1432 fieldValue = JPy_FROM_JINT(item);
1433 } else if (fieldType == JPy_JLong) {
1434 jlong item = (*jenv)->GetStaticLongField(jenv, declaringClass->classRef, fid);
1435 fieldValue = JPy_FROM_JLONG(item);
1436 } else if (fieldType == JPy_JFloat) {
1437 jfloat item = (*jenv)->GetStaticFloatField(jenv, declaringClass->classRef, fid);
1438 fieldValue = JPy_FROM_JFLOAT(item);
1439 } else if (fieldType == JPy_JDouble) {
1440 jdouble item = (*jenv)->GetStaticDoubleField(jenv, declaringClass->classRef, fid);
1441 fieldValue = JPy_FROM_JDOUBLE(item);
1442 } else if (fieldType == JPy_JString) {
1443 jstring objectRef = (*jenv)->GetStaticObjectField(jenv, declaringClass->classRef, fid);
1444 fieldValue = JPy_FromJString(jenv, objectRef);
1445 JPy_DELETE_LOCAL_REF(objectRef);
1446 } else {
1447 jobject objectRef = (*jenv)->GetStaticObjectField(jenv, declaringClass->classRef, fid);
1448 fieldValue = JPy_FromJObjectWithType(jenv, objectRef, (JPy_JType*) fieldType);
1449 JPy_DELETE_LOCAL_REF(objectRef);
1450 }
1451 PyDict_SetItem(typeDict, fieldName, fieldValue);
1452 return 0;
1453 }
1454
1455 int JType_ProcessField(JNIEnv* jenv, JPy_JType* declaringClass, PyObject* fieldKey, const char* fieldName, jclass fieldClassRef, jboolean isStatic, jboolean isFinal, jfieldID fid)
1456 {
1457 JPy_JField* field;
1458 JPy_JType* fieldType;
1459
1460 fieldType = JType_GetType(jenv, fieldClassRef, JNI_FALSE);
1461 if (fieldType == NULL) {
1462 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE + JPy_DIAG_F_ERR, "JType_ProcessField: WARNING: Java field '%s' rejected because an error occurred during type processing\n", fieldName);
1463 return -1;
1464 }
1465
1466 if (isStatic && isFinal) {
1467 // Add static final values to the JPy_JType's tp_dict.
1468 // todo: Note that this is a workaround only, because the JPy_JType's tp_getattro slot is not called.
1469 if (JType_AddFieldAttribute(jenv, declaringClass, fieldKey, fieldType, fid) < 0) {
1470 return -1;
1471 }
1472 } else if (!isStatic) {
1473 // Add instance field accessor to the JPy_JType's tp_dict, this will be evaluated in the JPy_JType's tp_setattro and tp_getattro slots.
1474 field = JField_New(declaringClass, fieldKey, fieldType, isStatic, isFinal, fid);
1475 if (field == NULL) {
1476 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE + JPy_DIAG_F_ERR, "JType_ProcessField: WARNING: Java field '%s' rejected because an error occurred during field instantiation\n", fieldName);
1477 return -1;
1478 }
1479
1480 if (JType_AcceptField(declaringClass, field)) {
1481 JType_AddField(declaringClass, field);
1482 } else {
1483 JField_Del(field);
1484 }
1485 } else {
1486 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE + JPy_DIAG_F_ERR, "JType_ProcessField: WARNING: Java field '%s' rejected because is is static, but not final\n", fieldName);
1487 }
1488
1489 return 0;
1490 }
1491
1492
1493 void JType_InitMethodParamDescriptorFunctions(JPy_JType* type, JPy_JMethod* method)
1494 {
1495 int index;
1496 for (index = 0; index < method->paramCount; index++) {
1497 JType_InitParamDescriptorFunctions(method->paramDescriptors + index, index == method->paramCount - 1 && method->isVarArgs);
1498 }
1499 }
1500
1501 int JType_AddMethod(JPy_JType* type, JPy_JMethod* method)
1502 {
1503 PyObject* typeDict;
1504 PyObject* methodValue;
1505 JPy_JOverloadedMethod* overloadedMethod;
1506
1507 typeDict = type->typeObj.tp_dict;
1508 if (typeDict == NULL) {
1509 PyErr_SetString(PyExc_RuntimeError, "jpy internal error: missing attribute '__dict__' in JType");
1510 return -1;
1511 }
1512
1513 // borrowed ref, no need to replace with PyDict_GetItemRef because typeDict won't be changed concurrently
1514 methodValue = PyDict_GetItem(typeDict, method->name);
1515 if (methodValue == NULL) {
1516 overloadedMethod = JOverloadedMethod_New(type, method->name, method);
1517 return PyDict_SetItem(typeDict, method->name, (PyObject*) overloadedMethod);
1518 } else if (PyObject_TypeCheck(methodValue, &JOverloadedMethod_Type)) {
1519 overloadedMethod = (JPy_JOverloadedMethod*) methodValue;
1520 return JOverloadedMethod_AddMethod(overloadedMethod, method);
1521 } else {
1522 PyErr_SetString(PyExc_RuntimeError, "jpy internal error: expected type 'JOverloadedMethod' in '__dict__' of a JType");
1523 return -1;
1524 }
1525 }
1526
1527 /**
1528 * Returns NULL (error), Py_None (borrowed ref), or a JPy_JOverloadedMethod* (borrowed ref)
1529 */
1530 PyObject* JType_GetOverloadedMethod(JNIEnv* jenv, JPy_JType* type, PyObject* methodName, jboolean useSuperClass)
1531 {
1532 PyObject* typeDict;
1533 PyObject* methodValue;
1534
1535 typeDict = type->typeObj.tp_dict;
1536 if (typeDict == NULL) {
1537 PyErr_SetString(PyExc_RuntimeError, "internal error: missing attribute '__dict__' in JType");
1538 return NULL;
1539 }
1540
1541 // borrowed ref, no need to replace with PyDict_GetItemRef because typeDict won't be changed concurrently
1542 methodValue = PyDict_GetItem(typeDict, methodName);
1543 if (methodValue == NULL) {
1544 if (useSuperClass) {
1545 // type->superType == NULL means that type->superType is either an interface or a java.lang.Object
1546 // If it is an interface (and not type java.lang.Object) also look for java.lang.Object methods
1547 // See https://github.com/bcdev/jpy/issues/57.
1548 if (type->superType != NULL) {
1549 return JType_GetOverloadedMethod(jenv, type->superType, methodName, JNI_TRUE);
1550 } else if (type != JPy_JObject && JPy_JObject != NULL) {
1551 return JType_GetOverloadedMethod(jenv, JPy_JObject, methodName, JNI_FALSE);
1552 } else {
1553 Py_RETURN_NONE;
1554 }
1555 } else {
1556 Py_RETURN_NONE;
1557 }
1558 }
1559
1560 if (PyObject_TypeCheck(methodValue, &JOverloadedMethod_Type)) {
1561 return methodValue;
1562 } else {
1563 PyErr_SetString(PyExc_RuntimeError, "internal error: expected type 'JOverloadedMethod' in '__dict__' of a JType");
1564 return NULL;
1565 }
1566 }
1567
1568 JPy_ReturnDescriptor* JType_CreateReturnDescriptor(JNIEnv* jenv, jclass returnClass)
1569 {
1570 JPy_ReturnDescriptor* returnDescriptor;
1571 JPy_JType* type;
1572
1573 returnDescriptor = PyMem_New(JPy_ReturnDescriptor, 1);
1574 if (returnDescriptor == NULL) {
1575 PyErr_NoMemory();
1576 return NULL;
1577 }
1578
1579 type = JType_GetType(jenv, returnClass, JNI_FALSE);
1580 if (type == NULL) {
1581 return NULL;
1582 }
1583
1584 returnDescriptor->type = type;
1585 returnDescriptor->paramIndex = -1;
1586 JPy_INCREF((PyObject*) type);
1587
1588 JPy_DIAG_PRINT(JPy_DIAG_F_TYPE, "JType_ProcessReturnType: type->javaName=\"%s\", type=%p\n", type->javaName, type);
1589
1590 return returnDescriptor;
1591 }
1592
1593
1594 JPy_ParamDescriptor* JType_CreateParamDescriptors(JNIEnv* jenv, int paramCount, jarray paramClasses)
1595 {
1596 JPy_ParamDescriptor* paramDescriptors;
1597 JPy_ParamDescriptor* paramDescriptor;
1598 JPy_JType* type;
1599 jclass paramClass;
1600 int i;
1601
1602 paramDescriptors = PyMem_New(JPy_ParamDescriptor, paramCount);
1603 if (paramDescriptors == NULL) {
1604 PyErr_NoMemory();
1605 return NULL;
1606 }
1607
1608 for (i = 0; i < paramCount; i++) {
1609 paramClass = (*jenv)->GetObjectArrayElement(jenv, paramClasses, i);
1610 paramDescriptor = paramDescriptors + i;
1611
1612 type = JType_GetType(jenv, paramClass, JNI_FALSE);
1613 JPy_DELETE_LOCAL_REF(paramClass);
1614 if (type == NULL) {
1615 return NULL;
1616 }
1617
1618 paramDescriptor->type = type;
1619 JPy_INCREF((PyObject*) paramDescriptor->type);
1620
1621 paramDescriptor->isMutable = 0;
1622 paramDescriptor->isOutput = 0;
1623 paramDescriptor->isReturn = 0;
1624 paramDescriptor->MatchPyArg = NULL;
1625 paramDescriptor->MatchVarArgPyArg = NULL;
1626 paramDescriptor->ConvertPyArg = NULL;
1627 paramDescriptor->ConvertVarArgPyArg = NULL;
1628 }
1629
1630 return paramDescriptors;
1631 }
1632
1633 int JType_MatchPyArgAsJBooleanParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1634 {
1635 if (PyBool_Check(pyArg)) return 100;
1636 else if (JPy_IS_CLONG(pyArg)) return 10;
1637 else return 0;
1638 }
1639
1640 int JType_ConvertPyArgToJBooleanArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1641 {
1642 value->z = JPy_AS_JBOOLEAN(pyArg);
1643 return 0;
1644 }
1645
1646 int JType_MatchPyArgAsJByteParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1647 {
1648 if (JPy_IS_CLONG(pyArg)) return 100;
1649 else if (PyBool_Check(pyArg)) return 10;
1650 else return 0;
1651 }
1652
1653 int JType_ConvertPyArgToJByteArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1654 {
1655 value->b = JPy_AS_JBYTE(pyArg);
1656 return 0;
1657 }
1658
1659 int JType_MatchPyArgAsJCharParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1660 {
1661 if (JPy_IS_CLONG(pyArg)) return 100;
1662 else if (PyBool_Check(pyArg)) return 10;
1663 else return 0;
1664 }
1665
1666 int JType_ConvertPyArgToJCharArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1667 {
1668 value->c = JPy_AS_JCHAR(pyArg);
1669 return 0;
1670 }
1671
1672 int JType_MatchPyArgAsJShortParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1673 {
1674 if (JPy_IS_CLONG(pyArg)) return 100;
1675 else if (PyBool_Check(pyArg)) return 10;
1676 else return 0;
1677 }
1678
1679 int JType_ConvertPyArgToJShortArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1680 {
1681 value->s = JPy_AS_JSHORT(pyArg);
1682 return 0;
1683 }
1684
1685 int JType_MatchPyArgAsJIntParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1686 {
1687 if (JPy_IS_CLONG(pyArg)) return 100;
1688 else if (PyBool_Check(pyArg)) return 10;
1689 else return 0;
1690 }
1691
1692 int JType_ConvertPyArgToJIntArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1693 {
1694 value->i = JPy_AS_JINT(pyArg);
1695 return 0;
1696 }
1697
1698 int JType_MatchPyArgAsJLongParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1699 {
1700 if (JPy_IS_CLONG(pyArg)) return 100;
1701 else if (PyBool_Check(pyArg)) return 10;
1702 else return 0;
1703 }
1704
1705 int JType_ConvertPyArgToJLongArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1706 {
1707 value->j = JPy_AS_JLONG(pyArg);
1708 return 0;
1709 }
1710
1711 int JType_MatchPyArgAsJFloatParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1712 {
1713 if (PyFloat_Check(pyArg)) return 90; // not 100, in order to give 'double' a chance
1714 else if (PyNumber_Check(pyArg)) return 50;
1715 else if (JPy_IS_CLONG(pyArg)) return 10;
1716 else if (PyBool_Check(pyArg)) return 1;
1717 else return 0;
1718 }
1719
1720 int JType_ConvertPyArgToJFloatArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1721 {
1722 value->f = JPy_AS_JFLOAT(pyArg);
1723 return 0;
1724 }
1725
1726 int JType_MatchPyArgAsJDoubleParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1727 {
1728 if (PyFloat_Check(pyArg)) return 100;
1729 else if (PyNumber_Check(pyArg)) return 50;
1730 else if (JPy_IS_CLONG(pyArg)) return 10;
1731 else if (PyBool_Check(pyArg)) return 1;
1732 else return 0;
1733 }
1734
1735 int JType_ConvertPyArgToJDoubleArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1736 {
1737 value->d = JPy_AS_JDOUBLE(pyArg);
1738 return 0;
1739 }
1740
1741 int JType_MatchPyArgAsJStringParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1742 {
1743 if (pyArg == Py_None) {
1744 // Signal it is possible, but give low priority since we cannot perform any type checks on 'None'
1745 return 1;
1746 }
1747 if (JPy_IS_STR(pyArg)) {
1748 return 100;
1749 }
1750 return 0;
1751 }
1752
1753 int JType_ConvertPyArgToJStringArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1754 {
1755 disposer->data = NULL;
1756 disposer->DisposeArg = JType_DisposeLocalObjectRefArg;
1757 return JPy_AsJString(jenv, pyArg, &value->l);
1758 }
1759
1760 int JType_ConvertPyArgToJPyObjectArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
1761 {
1762 disposer->data = NULL;
1763 disposer->DisposeArg = JType_DisposeLocalObjectRefArg;
1764 return JType_CreateJavaPyObject(jenv, JPy_JPyObject, pyArg, &value->l);
1765 }
1766
1767 int JType_MatchPyArgAsJPyObjectParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1768 {
1769 // We can always turn a python object into a PyObject
1770 // But it has a lower matching value to give a more specific type a better chance
1771 // ie, against:
1772 // void method1(String s) { ... }
1773 // void method1(PyObject o) { ... }
1774 //
1775 // the Python code: obj.method1('a string') should prefer the String specific version
1776 return 10; // yeah - EZ PZ
1777 }
1778
1779 int JType_MatchPyArgAsJObjectParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg)
1780 {
1781 return JType_MatchPyArgAsJObject(jenv, paramDescriptor->type, pyArg);
1782 }
1783
1784 int JType_MatchVarArgPyArgAsJObjectParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, int idx)
1785 {
1786 Py_ssize_t argCount = PyTuple_Size(pyArg);
1787 Py_ssize_t remaining = (argCount - idx);
1788
1789 JPy_JType *componentType = paramDescriptor->type->componentType;
1790 int minMatch = 100;
1791 int ii;
1792
1793 if (componentType == NULL) {
1794 return 0;
1795 }
1796
1797 if (remaining == 0) {
1798 return 10;
1799 }
1800
1801 for (ii = 0; ii < remaining; ii++) {
1802 PyObject *unpack = PyTuple_GetItem(pyArg, idx + ii);
1803 int matchValue = JType_MatchPyArgAsJObject(jenv, componentType, unpack);
1804 if (matchValue == 0) {
1805 return 0;
1806 }
1807 minMatch = matchValue < minMatch ? matchValue : minMatch;
1808 }
1809
1810 return minMatch;
1811 }
1812
1813 int JType_MatchVarArgPyArgAsJStringParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, int idx)
1814 {
1815 Py_ssize_t argCount = PyTuple_Size(pyArg);
1816 Py_ssize_t remaining = (argCount - idx);
1817
1818 JPy_JType *componentType = paramDescriptor->type->componentType;
1819 int minMatch = 100;
1820 int ii;
1821
1822 if (componentType != JPy_JString) {
1823 return 0;
1824 }
1825
1826 if (remaining == 0) {
1827 return 10;
1828 }
1829
1830 for (ii = 0; ii < remaining; ii++) {
1831 PyObject *unpack = PyTuple_GetItem(pyArg, idx + ii);
1832 int matchValue = JType_MatchPyArgAsJStringParam(jenv, paramDescriptor, unpack);
1833 if (matchValue == 0) {
1834 return 0;
1835 }
1836 minMatch = matchValue < minMatch ? matchValue : minMatch;
1837 }
1838
1839 return minMatch;
1840 }
1841
1842 int JType_MatchVarArgPyArgAsJPyObjectParam(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, int idx)
1843 {
1844 Py_ssize_t argCount = PyTuple_Size(pyArg);
1845 Py_ssize_t remaining = (argCount - idx);
1846
1847 JPy_JType *componentType = paramDescriptor->type->componentType;
1848 int minMatch = 100;
1849 int ii;
1850
1851 if (componentType != JPy_JPyObject) {
1852 return 0;
1853 }
1854
1855 if (remaining == 0) {
1856 return 10;
1857 }
1858
1859 for (ii = 0; ii < remaining; ii++) {
1860 PyObject *unpack = PyTuple_GetItem(pyArg, idx + ii);
1861 int matchValue = JType_MatchPyArgAsJPyObjectParam(jenv, paramDescriptor, unpack);
1862 if (matchValue == 0) {
1863 return 0;
1864 }
1865 minMatch = matchValue < minMatch ? matchValue : minMatch;
1866 }
1867 return minMatch;
1868 }
1869
1870 int JType_MatchVarArgPyArgAsJBooleanParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1871 {
1872 Py_ssize_t argCount = PyTuple_Size(pyArg);
1873 Py_ssize_t remaining = (argCount - idx);
1874
1875 JPy_JType *componentType = paramDescriptor->type->componentType;
1876 int minMatch = 100;
1877 int ii;
1878
1879 if (componentType != JPy_JBoolean) {
1880 // something is horribly wrong here!
1881 return 0;
1882 }
1883
1884 if (remaining == 0) {
1885 return 10;
1886 }
1887
1888 for (ii = 0; ii < remaining; ii++) {
1889 PyObject *unpack = PyTuple_GetItem(pyArg, idx + ii);
1890
1891 int matchValue;
1892 if (PyBool_Check(unpack)) matchValue = 100;
1893 else if (JPy_IS_CLONG(unpack)) matchValue = 10;
1894 else return 0;
1895 minMatch = matchValue < minMatch ? matchValue : minMatch;
1896 }
1897
1898 return minMatch;
1899 }
1900
1901 int JType_MatchVarArgPyArgAsJIntParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1902 {
1903 return JType_MatchVarArgPyArgIntType(paramDescriptor, pyArg, idx, JPy_JInt);
1904 }
1905
1906 int JType_MatchVarArgPyArgAsJLongParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1907 {
1908 return JType_MatchVarArgPyArgIntType(paramDescriptor, pyArg, idx, JPy_JLong);
1909 }
1910
1911 int JType_MatchVarArgPyArgAsJShortParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1912 {
1913 return JType_MatchVarArgPyArgIntType(paramDescriptor, pyArg, idx, JPy_JShort);
1914 }
1915
1916 int JType_MatchVarArgPyArgAsJByteParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1917 {
1918 return JType_MatchVarArgPyArgIntType(paramDescriptor, pyArg, idx, JPy_JByte);
1919 }
1920
1921 int JType_MatchVarArgPyArgAsJCharParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1922 {
1923 return JType_MatchVarArgPyArgIntType(paramDescriptor, pyArg, idx, JPy_JChar);
1924 }
1925
1926 int JType_MatchVarArgPyArgIntType(const JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx,
1927 struct JPy_JType *expectedComponentType) {
1928 Py_ssize_t argCount = PyTuple_Size(pyArg);
1929 Py_ssize_t remaining = (argCount - idx);
1930
1931 JPy_JType *componentType = paramDescriptor->type->componentType;
1932 int minMatch = 100;
1933 int ii;
1934
1935 if (componentType != expectedComponentType) {
1936 // something is horribly wrong here!
1937 return 0;
1938 }
1939
1940 if (remaining == 0) {
1941 return 10;
1942 }
1943
1944 for (ii = 0; ii < remaining; ii++) {
1945 PyObject *unpack = PyTuple_GetItem(pyArg, idx + ii);
1946
1947 int matchValue;
1948 if (JPy_IS_CLONG(unpack)) matchValue = 100;
1949 else if (PyBool_Check(unpack)) matchValue = 10;
1950 else return 0;
1951 minMatch = matchValue < minMatch ? matchValue : minMatch;
1952 }
1953
1954 return minMatch;
1955 }
1956
1957 int JType_MatchVarArgPyArgAsJDoubleParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1958 {
1959 return JType_MatchVarArgPyArgAsFPType(paramDescriptor, pyArg, idx, JPy_JDouble, 100);
1960 }
1961
1962 int JType_MatchVarArgPyArgAsJFloatParam(JNIEnv *jenv, JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx)
1963 {
1964 // float gets a match of 90, so that double has a better chance
1965 return JType_MatchVarArgPyArgAsFPType(paramDescriptor, pyArg, idx, JPy_JFloat, 90);
1966 }
1967
1968 /* The float and double match functions are almost identical, but for the expected componentType and the match value
1969 * for floating point numbers should give a preference to double over float. */
1970 int JType_MatchVarArgPyArgAsFPType(const JPy_ParamDescriptor *paramDescriptor, PyObject *pyArg, int idx,
1971 struct JPy_JType *expectedType, int floatMatch) {
1972 Py_ssize_t argCount = PyTuple_Size(pyArg);
1973 Py_ssize_t remaining = (argCount - idx);
1974
1975 JPy_JType *componentType = paramDescriptor->type->componentType;
1976 int minMatch = 100;
1977 int ii;
1978
1979 if (componentType != expectedType) {
1980 // something is horribly wrong here!
1981 return 0;
1982 }
1983
1984 if (remaining == 0) {
1985 return 10;
1986 }
1987
1988 for (ii = 0; ii < remaining; ii++) {
1989 PyObject *unpack = PyTuple_GetItem(pyArg, idx + ii);
1990
1991 int matchValue;
1992 if (PyFloat_Check(unpack)) matchValue = floatMatch;
1993 else if (PyNumber_Check(unpack)) matchValue = 50;
1994 else if (JPy_IS_CLONG(unpack)) matchValue = 10;
1995 else if (PyBool_Check(unpack)) matchValue = 1;
1996 else return 0;
1997 minMatch = matchValue < minMatch ? matchValue : minMatch;
1998 }
1999
2000 return minMatch;
2001 }
2002
2003 int JType_ConvertVarArgPyArgToJObjectArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArgOrig, int offset, jvalue* value, JPy_ArgDisposer* disposer)
2004 {
2005 Py_ssize_t size = PyTuple_Size(pyArgOrig);
2006 PyObject *pyArg = PyTuple_GetSlice(pyArgOrig, offset, size);
2007
2008 if (pyArg == Py_None) {
2009 // Py_None maps to (Java) NULL
2010 value->l = NULL;
2011 disposer->data = NULL;
2012 disposer->DisposeArg = NULL;
2013 } else if (JObj_Check(pyArg)) {
2014 // If it is a wrapped Java object, it is always a global reference, so don't dispose it
2015 JPy_JObj* obj = (JPy_JObj*) pyArg;
2016 value->l = obj->objectRef;
2017 disposer->data = NULL;
2018 disposer->DisposeArg = NULL;
2019 } else {
2020 // For any other Python argument, we first check if the formal parameter is a primitive array
2021 // and the Python argument is a buffer object
2022
2023 JPy_JType* paramType = paramDescriptor->type;
2024 JPy_JType* paramComponentType = paramType->componentType;
2025
2026 if (paramComponentType != NULL && paramComponentType->isPrimitive && PyObject_CheckBuffer(pyArg)) {
2027 Py_buffer* pyBuffer;
2028 int flags;
2029 Py_ssize_t itemCount;
2030 jarray jArray;
2031 void* arrayItems;
2032 jint itemSize;
2033
2034 pyBuffer = PyMem_New(Py_buffer, 1);
2035 if (pyBuffer == NULL) {
2036 PyErr_NoMemory();
2037 JPy_DECREF(pyArg);
2038 return -1;
2039 }
2040
2041 flags = paramDescriptor->isMutable ? PyBUF_WRITABLE : PyBUF_SIMPLE;
2042 if (PyObject_GetBuffer(pyArg, pyBuffer, flags) < 0) {
2043 PyMem_Del(pyBuffer);
2044 JPy_DECREF(pyArg);
2045 return -1;
2046 }
2047
2048 itemCount = pyBuffer->len / pyBuffer->itemsize;
2049
2050 if (paramComponentType == JPy_JBoolean) {
2051 jArray = (*jenv)->NewBooleanArray(jenv, itemCount);
2052 itemSize = sizeof(jboolean);
2053 } else if (paramComponentType == JPy_JByte) {
2054 jArray = (*jenv)->NewByteArray(jenv, itemCount);
2055 itemSize = sizeof(jbyte);
2056 } else if (paramComponentType == JPy_JChar) {
2057 jArray = (*jenv)->NewCharArray(jenv, itemCount);
2058 itemSize = sizeof(jchar);
2059 } else if (paramComponentType == JPy_JShort) {
2060 jArray = (*jenv)->NewShortArray(jenv, itemCount);
2061 itemSize = sizeof(jshort);
2062 } else if (paramComponentType == JPy_JInt) {
2063 jArray = (*jenv)->NewIntArray(jenv, itemCount);
2064 itemSize = sizeof(jint);
2065 } else if (paramComponentType == JPy_JLong) {
2066 jArray = (*jenv)->NewLongArray(jenv, itemCount);
2067 itemSize = sizeof(jlong);
2068 } else if (paramComponentType == JPy_JFloat) {
2069 jArray = (*jenv)->NewFloatArray(jenv, itemCount);
2070 itemSize = sizeof(jfloat);
2071 } else if (paramComponentType == JPy_JDouble) {
2072 jArray = (*jenv)->NewDoubleArray(jenv, itemCount);
2073 itemSize = sizeof(jdouble);
2074 } else {
2075 JPy_DECREF(pyArg);
2076 PyBuffer_Release(pyBuffer);
2077 PyMem_Del(pyBuffer);
2078 PyErr_SetString(PyExc_RuntimeError, "internal error: illegal primitive Java type");
2079 return -1;
2080 }
2081
2082 if (pyBuffer->len != itemCount * itemSize) {
2083 Py_ssize_t bufferLen = pyBuffer->len;
2084 Py_ssize_t bufferItemSize = pyBuffer->itemsize;
2085 //printf("%ld, %ld, %ld, %ld\n", pyBuffer->len , pyBuffer->itemsize, itemCount, itemSize);
2086 JPy_DECREF(pyArg);
2087 PyBuffer_Release(pyBuffer);
2088 PyMem_Del(pyBuffer);
2089 PyErr_Format(PyExc_ValueError,
2090 "illegal buffer argument: expected size was %ld bytes, but got %ld (expected item size was %d bytes, got %ld)",
2091 itemCount * itemSize, bufferLen, itemSize, bufferItemSize);
2092 return -1;
2093 }
2094
2095 if (jArray == NULL) {
2096 JPy_DECREF(pyArg);
2097 PyBuffer_Release(pyBuffer);
2098 PyMem_Del(pyBuffer);
2099 PyErr_NoMemory();
2100 return -1;
2101 }
2102
2103 if (!paramDescriptor->isOutput) {
2104 arrayItems = (*jenv)->GetPrimitiveArrayCritical(jenv, jArray, NULL);
2105 if (arrayItems == NULL) {
2106 JPy_DECREF(pyArg);
2107 PyBuffer_Release(pyBuffer);
2108 PyMem_Del(pyBuffer);
2109 PyErr_NoMemory();
2110 return -1;
2111 }
2112 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC|JPy_DIAG_F_MEM, "JType_ConvertPyArgToJObjectArg: moving Python buffer into Java array: pyBuffer->buf=%p, pyBuffer->len=%d\n", pyBuffer->buf, pyBuffer->len);
2113 memcpy(arrayItems, pyBuffer->buf, itemCount * itemSize);
2114 (*jenv)->ReleasePrimitiveArrayCritical(jenv, jArray, arrayItems, 0);
2115 }
2116
2117 value->l = jArray;
2118 disposer->data = pyBuffer;
2119 disposer->DisposeArg = paramDescriptor->isMutable ? JType_DisposeWritableBufferArg : JType_DisposeReadOnlyBufferArg;
2120 } else {
2121 jobject objectRef;
2122 if (JType_ConvertPythonToJavaObject(jenv, paramType, pyArg, &objectRef, JNI_FALSE) < 0) {
2123 JPy_DECREF(pyArg);
2124 return -1;
2125 }
2126 value->l = objectRef;
2127 disposer->data = NULL;
2128 disposer->DisposeArg = JType_DisposeLocalObjectRefArg;
2129 }
2130 }
2131
2132 JPy_DECREF(pyArg);
2133
2134 return 0;
2135 }
2136
2137 int JType_MatchPyArgAsJObject(JNIEnv* jenv, JPy_JType* paramType, PyObject* pyArg)
2138 {
2139 JPy_JType* argType;
2140 JPy_JType* paramComponentType;
2141 JPy_JType* argComponentType;
2142 JPy_JObj* argValue;
2143
2144 if (pyArg == Py_None) {
2145 // Signal it is possible, but give low priority since we cannot perform any type checks on 'None'
2146 return 1;
2147 }
2148
2149 paramComponentType = paramType->componentType;
2150
2151 if (JObj_Check(pyArg)) {
2152 // pyArg is a Java object
2153
2154 argType = (JPy_JType*) Py_TYPE(pyArg);
2155 if (argType == paramType) {
2156 // pyArg has same type as the parameter
2157 return 100;
2158 }
2159
2160 argValue = (JPy_JObj*) pyArg;
2161 if ((*jenv)->IsInstanceOf(jenv, argValue->objectRef, paramType->classRef)) {
2162 argComponentType = argType->componentType;
2163 if (argComponentType == paramComponentType) {
2164 // pyArg is an instance of parameter type, and they both have the same component types (which may be null)
2165 return 90;
2166 }
2167 if (argComponentType != NULL && paramComponentType != NULL) {
2168 // Determines whether an object of clazz1 can be safely cast to clazz2.
2169 if ((*jenv)->IsAssignableFrom(jenv, argComponentType->classRef, paramComponentType->classRef)) {
2170 // pyArg is an instance of parameter array type, and component types are compatible
2171 return 80;
2172 }
2173 }
2174 // Honour that pyArg is compatible with paramType, but better matches may exist.
2175 return 10;
2176 }
2177
2178 // pyArg type does not match parameter type
2179 return 0;
2180 }
2181
2182 // pyArg is not a Java object
2183
2184 if (paramComponentType != NULL) {
2185 // The parameter type is an array type
2186
2187 if (paramComponentType->isPrimitive && PyObject_CheckBuffer(pyArg)) {
2188 Py_buffer view;
2189
2190 // The parameter type is a primitive array type, pyArg is a Python buffer object
2191
2192 if (PyObject_GetBuffer(pyArg, &view, PyBUF_FORMAT) == 0) {
2193 JPy_JType* type;
2194 int matchValue;
2195
2196 //printf("JType_AssessToJObject: buffer len=%d, itemsize=%d, format=%s\n", view.len, view.itemsize, view.format);
2197
2198 type = paramComponentType;
2199 matchValue = 0;
2200 if (view.format != NULL) {
2201 char format = *view.format;
2202 if (type == JPy_JBoolean) {
2203 matchValue = format == 'b' || format == 'B' ? 100
2204 : view.itemsize == 1 ? 10
2205 : 0;
2206 } else if (type == JPy_JByte) {
2207 matchValue = format == 'b' ? 100
2208 : format == 'B' ? 90
2209 : view.itemsize == 1 ? 10
2210 : 0;
2211 } else if (type == JPy_JChar) {
2212 matchValue = format == 'u' ? 100
2213 : format == 'H' ? 90
2214 : format == 'h' ? 80
2215 : view.itemsize == 2 ? 10
2216 : 0;
2217 } else if (type == JPy_JShort) {
2218 matchValue = format == 'h' ? 100
2219 : format == 'H' ? 90
2220 : view.itemsize == 2 ? 10
2221 : 0;
2222 } else if (type == JPy_JInt) {
2223 matchValue = format == 'i' ? 100
2224 : format == 'I' ? 90
2225 : view.itemsize == 4 ? 10
2226 : 0;
2227 } else if (type == JPy_JLong) {
2228 matchValue = format == 'q' || format == 'l' ? 100
2229 : format == 'Q' || format == 'L' ? 90
2230 : view.itemsize == 8 ? 10
2231 : 0;
2232 } else if (type == JPy_JFloat) {
2233 matchValue = format == 'f' ? 100
2234 : view.itemsize == 4 ? 10
2235 : 0;
2236 } else if (type == JPy_JDouble) {
2237 matchValue = format == 'd' ? 100
2238 : view.itemsize == 8 ? 10
2239 : 0;
2240 }
2241 } else {
2242 if (type == JPy_JBoolean) {
2243 matchValue = view.itemsize == 1 ? 10 : 0;
2244 } else if (type == JPy_JByte) {
2245 matchValue = view.itemsize == 1 ? 10 : 0;
2246 } else if (type == JPy_JChar) {
2247 matchValue = view.itemsize == 2 ? 10 : 0;
2248 } else if (type == JPy_JShort) {
2249 matchValue = view.itemsize == 2 ? 10 : 0;
2250 } else if (type == JPy_JInt) {
2251 matchValue = view.itemsize == 4 ? 10 : 0;
2252 } else if (type == JPy_JLong) {
2253 matchValue = view.itemsize == 8 ? 10 : 0;
2254 } else if (type == JPy_JFloat) {
2255 matchValue = view.itemsize == 4 ? 10 : 0;
2256 } else if (type == JPy_JDouble) {
2257 matchValue = view.itemsize == 8 ? 10 : 0;
2258 }
2259 }
2260
2261 PyBuffer_Release(&view);
2262 return matchValue;
2263 }
2264 } else if (PySequence_Check(pyArg)) {
2265 // if we know the type of the array is a string, we should preferentially match it
2266 if ((*jenv)->IsAssignableFrom(jenv, paramComponentType->classRef, JPy_String_JClass)) {
2267 // it's a string array
2268 Py_ssize_t len = PySequence_Length(pyArg);
2269 Py_ssize_t ii;
2270
2271 for (ii = 0; ii < len; ++ii) {
2272 PyObject *element = PySequence_GetItem(pyArg, ii);
2273 if (!JPy_IS_STR(element)) {
2274 // if the element is not a string, this is not a good match
2275 return 0;
2276 }
2277 }
2278
2279 // a String sequence is a good match for a String array
2280 return 80;
2281 }
2282 return 10;
2283 }
2284 } else if (paramType == JPy_JObject) {
2285 // Parameter type is not an array type, but any other Java object type
2286 return 10;
2287 } else if (paramType == JPy_JBooleanObj) {
2288 if (PyBool_Check(pyArg)) {
2289 return 100;
2290 } else if (JPy_IS_CLONG(pyArg)) {
2291 return 10;
2292 }
2293 } else if (paramType == JPy_JCharacterObj
2294 || paramType == JPy_JByteObj
2295 || paramType == JPy_JShortObj
2296 || paramType == JPy_JIntegerObj
2297 || paramType == JPy_JLongObj) {
2298 if (JPy_IS_CLONG(pyArg)) {
2299 return 100;
2300 } else if (PyBool_Check(pyArg)) {
2301 return 10;
2302 }
2303 } else if (paramType == JPy_JFloatObj
2304 || paramType == JPy_JDoubleObj) {
2305 if (PyFloat_Check(pyArg)) {
2306 return 100;
2307 } else if (JPy_IS_CLONG(pyArg)) {
2308 return 90;
2309 } else if (PyBool_Check(pyArg)) {
2310 return 10;
2311 }
2312 } else {
2313 if (JPy_IS_STR(pyArg)) {
2314 if ((*jenv)->IsAssignableFrom(jenv, JPy_JString->classRef, paramType->classRef)) {
2315 return 80;
2316 }
2317 }
2318 else if (PyBool_Check(pyArg)) {
2319 if ((*jenv)->IsAssignableFrom(jenv, JPy_Boolean_JClass, paramType->classRef)) {
2320 return 80;
2321 }
2322 }
2323 else if (JPy_IS_CLONG(pyArg)) {
2324 if ((*jenv)->IsAssignableFrom(jenv, JPy_Integer_JClass, paramType->classRef)) {
2325 return 80;
2326 }
2327 else if ((*jenv)->IsAssignableFrom(jenv, JPy_Long_JClass, paramType->classRef)) {
2328 return 80;
2329 }
2330 }
2331 else if (PyFloat_Check(pyArg)) {
2332 if ((*jenv)->IsAssignableFrom(jenv, JPy_Double_JClass, paramType->classRef)) {
2333 return 80;
2334 }
2335 else if ((*jenv)->IsAssignableFrom(jenv, JPy_Float_JClass, paramType->classRef)) {
2336 return 80;
2337 }
2338 }
2339 }
2340
2341 return 0;
2342 }
2343
2344 int JType_ConvertPyArgToJObjectArg(JNIEnv* jenv, JPy_ParamDescriptor* paramDescriptor, PyObject* pyArg, jvalue* value, JPy_ArgDisposer* disposer)
2345 {
2346 if (pyArg == Py_None) {
2347 // Py_None maps to (Java) NULL
2348 value->l = NULL;
2349 disposer->data = NULL;
2350 disposer->DisposeArg = NULL;
2351 } else if (JObj_Check(pyArg)) {
2352 // If it is a wrapped Java object, it is always a global reference, so don't dispose it
2353 JPy_JObj* obj = (JPy_JObj*) pyArg;
2354 value->l = obj->objectRef;
2355 disposer->data = NULL;
2356 disposer->DisposeArg = NULL;
2357 } else {
2358 // For any other Python argument, we first check if the formal parameter is a primitive array
2359 // and the Python argument is a buffer object
2360
2361 JPy_JType* paramType = paramDescriptor->type;
2362 JPy_JType* paramComponentType = paramType->componentType;
2363
2364 if (paramComponentType != NULL && paramComponentType->isPrimitive && PyObject_CheckBuffer(pyArg)) {
2365 Py_buffer* pyBuffer;
2366 int flags;
2367 Py_ssize_t itemCount;
2368 jarray jArray;
2369 void* arrayItems;
2370 jint itemSize;
2371
2372 pyBuffer = PyMem_New(Py_buffer, 1);
2373 if (pyBuffer == NULL) {
2374 PyErr_NoMemory();
2375 return -1;
2376 }
2377
2378 flags = paramDescriptor->isMutable ? PyBUF_WRITABLE : PyBUF_SIMPLE;
2379 if (PyObject_GetBuffer(pyArg, pyBuffer, flags) < 0) {
2380 PyMem_Del(pyBuffer);
2381 return -1;
2382 }
2383
2384 itemCount = pyBuffer->len / pyBuffer->itemsize;
2385
2386 if (paramComponentType == JPy_JBoolean) {
2387 jArray = (*jenv)->NewBooleanArray(jenv, itemCount);
2388 itemSize = sizeof(jboolean);
2389 } else if (paramComponentType == JPy_JByte) {
2390 jArray = (*jenv)->NewByteArray(jenv, itemCount);
2391 itemSize = sizeof(jbyte);
2392 } else if (paramComponentType == JPy_JChar) {
2393 jArray = (*jenv)->NewCharArray(jenv, itemCount);
2394 itemSize = sizeof(jchar);
2395 } else if (paramComponentType == JPy_JShort) {
2396 jArray = (*jenv)->NewShortArray(jenv, itemCount);
2397 itemSize = sizeof(jshort);
2398 } else if (paramComponentType == JPy_JInt) {
2399 jArray = (*jenv)->NewIntArray(jenv, itemCount);
2400 itemSize = sizeof(jint);
2401 } else if (paramComponentType == JPy_JLong) {
2402 jArray = (*jenv)->NewLongArray(jenv, itemCount);
2403 itemSize = sizeof(jlong);
2404 } else if (paramComponentType == JPy_JFloat) {
2405 jArray = (*jenv)->NewFloatArray(jenv, itemCount);
2406 itemSize = sizeof(jfloat);
2407 } else if (paramComponentType == JPy_JDouble) {
2408 jArray = (*jenv)->NewDoubleArray(jenv, itemCount);
2409 itemSize = sizeof(jdouble);
2410 } else {
2411 PyBuffer_Release(pyBuffer);
2412 PyMem_Del(pyBuffer);
2413 PyErr_SetString(PyExc_RuntimeError, "internal error: illegal primitive Java type");
2414 return -1;
2415 }
2416
2417 if (pyBuffer->len != itemCount * itemSize) {
2418 Py_ssize_t bufferLen = pyBuffer->len;
2419 Py_ssize_t bufferItemSize = pyBuffer->itemsize;
2420 //printf("%ld, %ld, %ld, %ld\n", pyBuffer->len , pyBuffer->itemsize, itemCount, itemSize);
2421 PyBuffer_Release(pyBuffer);
2422 PyMem_Del(pyBuffer);
2423 PyErr_Format(PyExc_ValueError,
2424 "illegal buffer argument: expected size was %ld bytes, but got %ld (expected item size was %d bytes, got %ld)",
2425 itemCount * itemSize, bufferLen, itemSize, bufferItemSize);
2426 return -1;
2427 }
2428
2429 if (jArray == NULL) {
2430 PyBuffer_Release(pyBuffer);
2431 PyMem_Del(pyBuffer);
2432 PyErr_NoMemory();
2433 return -1;
2434 }
2435
2436 if (!paramDescriptor->isOutput) {
2437 arrayItems = (*jenv)->GetPrimitiveArrayCritical(jenv, jArray, NULL);
2438 if (arrayItems == NULL) {
2439 PyBuffer_Release(pyBuffer);
2440 PyMem_Del(pyBuffer);
2441 PyErr_NoMemory();
2442 return -1;
2443 }
2444 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC|JPy_DIAG_F_MEM, "JType_ConvertPyArgToJObjectArg: moving Python buffer into Java array: pyBuffer->buf=%p, pyBuffer->len=%d\n", pyBuffer->buf, pyBuffer->len);
2445 memcpy(arrayItems, pyBuffer->buf, itemCount * itemSize);
2446 (*jenv)->ReleasePrimitiveArrayCritical(jenv, jArray, arrayItems, 0);
2447 }
2448
2449 value->l = jArray;
2450 disposer->data = pyBuffer;
2451 disposer->DisposeArg = paramDescriptor->isMutable ? JType_DisposeWritableBufferArg : JType_DisposeReadOnlyBufferArg;
2452 } else {
2453 jobject objectRef;
2454 if (JType_ConvertPythonToJavaObject(jenv, paramType, pyArg, &objectRef, JNI_FALSE) < 0) {
2455 return -1;
2456 }
2457 value->l = objectRef;
2458 disposer->data = NULL;
2459 disposer->DisposeArg = JType_DisposeLocalObjectRefArg;
2460 }
2461 }
2462
2463 return 0;
2464 }
2465
2466 void JType_DisposeLocalObjectRefArg(JNIEnv* jenv, jvalue* value, void* data)
2467 {
2468 jobject objectRef = value->l;
2469 if (objectRef != NULL) {
2470 JPy_DIAG_PRINT(JPy_DIAG_F_MEM, "JType_DisposeLocalObjectRefArg: objectRef=%p\n", objectRef);
2471 JPy_DELETE_LOCAL_REF(objectRef);
2472 }
2473 }
2474
2475 void JType_DisposeReadOnlyBufferArg(JNIEnv* jenv, jvalue* value, void* data)
2476 {
2477 Py_buffer* pyBuffer;
2478 jarray jArray;
2479
2480 pyBuffer = (Py_buffer*) data;
2481 jArray = (jarray) value->l;
2482
2483 JPy_DIAG_PRINT(JPy_DIAG_F_MEM, "JType_DisposeReadOnlyBufferArg: pyBuffer=%p, jArray=%p\n", pyBuffer, jArray);
2484
2485 if (pyBuffer != NULL) {
2486 PyBuffer_Release(pyBuffer);
2487 PyMem_Del(pyBuffer);
2488 }
2489 if (jArray != NULL) {
2490 JPy_DELETE_LOCAL_REF(jArray);
2491 }
2492 }
2493
2494 void JType_DisposeWritableBufferArg(JNIEnv* jenv, jvalue* value, void* data)
2495 {
2496 Py_buffer* pyBuffer;
2497 jarray jArray;
2498 void* arrayItems;
2499
2500 pyBuffer = (Py_buffer*) data;
2501 jArray = (jarray) value->l;
2502
2503 JPy_DIAG_PRINT(JPy_DIAG_F_MEM, "JType_DisposeWritableBufferArg: pyBuffer=%p, jArray=%p\n", pyBuffer, jArray);
2504
2505 if (pyBuffer != NULL && jArray != NULL) {
2506 // Copy modified array content back into buffer view
2507 arrayItems = (*jenv)->GetPrimitiveArrayCritical(jenv, jArray, NULL);
2508 if (arrayItems != NULL) {
2509 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC|JPy_DIAG_F_MEM, "JType_DisposeWritableBufferArg: moving Java array into Python buffer: pyBuffer->buf=%p, pyBuffer->len=%d\n", pyBuffer->buf, pyBuffer->len);
2510 memcpy(pyBuffer->buf, arrayItems, pyBuffer->len);
2511 (*jenv)->ReleasePrimitiveArrayCritical(jenv, jArray, arrayItems, 0);
2512 }
2513 JPy_DELETE_LOCAL_REF(jArray);
2514 PyBuffer_Release(pyBuffer);
2515 PyMem_Del(pyBuffer);
2516 } else if (pyBuffer != NULL) {
2517 PyBuffer_Release(pyBuffer);
2518 PyMem_Del(pyBuffer);
2519 } else if (jArray != NULL) {
2520 JPy_DELETE_LOCAL_REF(jArray);
2521 }
2522 }
2523
2524 void JType_InitParamDescriptorFunctions(JPy_ParamDescriptor* paramDescriptor, jboolean isLastVarArg)
2525 {
2526 JPy_JType* paramType = paramDescriptor->type;
2527
2528 if (paramType == JPy_JVoid) {
2529 paramDescriptor->MatchPyArg = NULL;
2530 paramDescriptor->ConvertPyArg = NULL;
2531 } else if (paramType == JPy_JBoolean) {
2532 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJBooleanParam;
2533 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJBooleanArg;
2534 } else if (paramType == JPy_JByte) {
2535 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJByteParam;
2536 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJByteArg;
2537 } else if (paramType == JPy_JChar) {
2538 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJCharParam;
2539 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJCharArg;
2540 } else if (paramType == JPy_JShort) {
2541 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJShortParam;
2542 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJShortArg;
2543 } else if (paramType == JPy_JInt) {
2544 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJIntParam;
2545 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJIntArg;
2546 } else if (paramType == JPy_JLong) {
2547 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJLongParam;
2548 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJLongArg;
2549 } else if (paramType == JPy_JFloat) {
2550 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJFloatParam;
2551 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJFloatArg;
2552 } else if (paramType == JPy_JDouble) {
2553 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJDoubleParam;
2554 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJDoubleArg;
2555 } else if (paramType == JPy_JString) {
2556 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJStringParam;
2557 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJStringArg;
2558 //} else if (paramType == JPy_JMap) {
2559 //} else if (paramType == JPy_JList) {
2560 //} else if (paramType == JPy_JSet) {
2561 } else if (paramType == JPy_JPyObject) {
2562 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJPyObjectParam;
2563 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJPyObjectArg;
2564 } else {
2565 paramDescriptor->MatchPyArg = JType_MatchPyArgAsJObjectParam;
2566 paramDescriptor->ConvertPyArg = JType_ConvertPyArgToJObjectArg;
2567 }
2568 if (isLastVarArg) {
2569 paramDescriptor->ConvertVarArgPyArg = JType_ConvertVarArgPyArgToJObjectArg;
2570
2571 if (paramType->componentType == JPy_JBoolean) {
2572 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJBooleanParam;
2573 } else if (paramType->componentType == JPy_JByte) {
2574 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJByteParam;
2575 } else if (paramType->componentType == JPy_JChar) {
2576 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJCharParam;
2577 } else if (paramType->componentType == JPy_JShort) {
2578 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJShortParam;
2579 } else if (paramType->componentType == JPy_JInt) {
2580 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJIntParam;
2581 } else if (paramType->componentType == JPy_JLong) {
2582 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJLongParam;
2583 } else if (paramType->componentType == JPy_JFloat) {
2584 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJFloatParam;
2585 } else if (paramType->componentType == JPy_JDouble) {
2586 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJDoubleParam;
2587 } else if (paramType->componentType == JPy_JString) {
2588 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJStringParam;
2589 } else if (paramType->componentType == JPy_JPyObject) {
2590 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJPyObjectParam;
2591 } else {
2592 paramDescriptor->MatchVarArgPyArg = JType_MatchVarArgPyArgAsJObjectParam;
2593 }
2594 }
2595 }
2596
2597 /**
2598 * The JType's tp_repr slot.
2599 */
2600 PyObject* JType_repr(JPy_JType* self)
2601 {
2602 //printf("JType_repr: self=%p\n", self);
2603 return JPy_FROM_FORMAT("%s(%p)",
2604 self->javaName,
2605 self->classRef);
2606 }
2607
2608 /**
2609 * The JType's tp_str slot.
2610 */
2611 PyObject* JType_str(JPy_JType* self)
2612 {
2613 JNIEnv* jenv;
2614 jstring strJObj;
2615 PyObject* strPyObj;
2616 jboolean isCopy;
2617 const char * utfChars;
2618
2619 JPy_GET_JNI_ENV_OR_RETURN(jenv, NULL)
2620
2621 //printf("JType_str: self=%p\n", self);
2622
2623 strJObj = (*jenv)->CallObjectMethod(jenv, self->classRef, JPy_Object_ToString_MID);
2624 utfChars = (*jenv)->GetStringUTFChars(jenv, strJObj, &isCopy);
2625 strPyObj = JPy_FROM_FORMAT("%s", utfChars);
2626 (*jenv)->ReleaseStringUTFChars(jenv, strJObj, utfChars);
2627 JPy_DELETE_LOCAL_REF(strJObj);
2628
2629 return strPyObj;
2630 }
2631
2632 /**
2633 * The JType's tp_dealloc slot.
2634 */
2635 void JType_dealloc(JPy_JType* self)
2636 {
2637 JNIEnv* jenv = JPy_GetJNIEnv();
2638
2639 //printf("JType_dealloc: self->javaName='%s', self->classRef=%p\n", self->javaName, self->classRef);
2640
2641 PyMem_Del(self->javaName);
2642 self->javaName = NULL;
2643
2644 if (jenv != NULL && self->classRef != NULL) {
2645 (*jenv)->DeleteGlobalRef(jenv, self->classRef);
2646 self->classRef = NULL;
2647 }
2648
2649 JPy_XDECREF(self->superType);
2650 self->superType = NULL;
2651
2652 JPy_XDECREF(self->componentType);
2653 self->componentType = NULL;
2654
2655 Py_TYPE(self)->tp_free((PyObject*) self);
2656 }
2657
2658 /**
2659 * The JType's JType_getattro slot.
2660 */
2661 PyObject* JType_getattro(JPy_JType* self, PyObject* name)
2662 {
2663 //printf("JType_getattro: %s.%s\n", Py_TYPE(self)->tp_name, JPy_AS_UTF8(name));
2664
2665 if (!self->isResolved && !self->isResolving) {
2666 JNIEnv* jenv;
2667 JPy_GET_JNI_ENV_OR_RETURN(jenv, NULL);
2668 JType_ResolveType(jenv, self);
2669 }
2670
2671 return PyObject_GenericGetAttr((PyObject*) self, name);
2672 }
2673
2674
2675 /**
2676 * The jpy.JType singleton.
2677 */
2678 PyTypeObject JType_Type = {
2679 PyVarObject_HEAD_INIT(NULL, 0)
2680 "jpy.JType", /* tp_name */
2681 sizeof (JPy_JType), /* tp_basicsize */
2682 0, /* tp_itemsize */
2683 (destructor) JType_dealloc, /* tp_dealloc */
2684 0, /* tp_print */
2685 NULL, /* tp_getattr */
2686 NULL, /* tp_setattr */
2687 NULL, /* tp_reserved */
2688 (reprfunc) JType_repr, /* tp_repr */
2689 NULL, /* tp_as_number */
2690 NULL, /* tp_as_sequence */
2691 NULL, /* tp_as_mapping */
2692 NULL, /* tp_hash */
2693 NULL, /* tp_call */
2694 (reprfunc) JType_str, /* tp_str */
2695 (getattrofunc)JType_getattro, /* tp_getattro */
2696 NULL, /* tp_setattro */
2697 NULL, /* tp_as_buffer */
2698 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
2699 "Java Meta Type", /* tp_doc */
2700 NULL, /* tp_traverse */
2701 NULL, /* tp_clear */
2702 NULL, /* tp_richcompare */
2703 0, /* tp_weaklistoffset */
2704 NULL, /* tp_iter */
2705 NULL, /* tp_iternext */
2706 NULL, /* tp_methods */
2707 NULL, /* tp_members */
2708 NULL, /* tp_getset */
2709 NULL, /* tp_base */
2710 NULL, /* tp_dict */
2711 NULL, /* tp_descr_get */
2712 NULL, /* tp_descr_set */
2713 0, /* tp_dictoffset */
2714 (initproc) NULL, /* tp_init */
2715 NULL, /* tp_alloc */
2716 (newfunc) NULL, /* tp_new=NULL --> JType instances cannot be created from Python. */
2717 };