Debian Codegraph @

src/main/c/jni/org_jpy_PyLib.c

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
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 <jni.h>
21 #include <Python.h>
22 #include "frameobject.h"
23
24 #include "jpy_module.h"
25 #include "jpy_diag.h"
26 #include "jpy_jtype.h"
27 #include "jpy_jobj.h"
28 #include "jpy_conv.h"
29
30 #include "org_jpy_PyLib.h"
31 #include "org_jpy_PyLib_Diag.h"
32
33 // Note: Native org.jpy.PyLib function definition headers in this file are formatted according to the header
34 // generated by javah. This makes it easier to follow up changes in the header.
35
36 PyObject* PyLib_GetAttributeObject(JNIEnv* jenv, PyObject* pyValue, jstring jName);
37 PyObject* PyLib_CallAndReturnObject(JNIEnv *jenv, PyObject* pyValue, jboolean isMethodCall, jstring jName, jint argCount, jobjectArray jArgs, jobjectArray jParamClasses);
38 void PyLib_HandlePythonException(JNIEnv* jenv);
39 void PyLib_ThrowOOM(JNIEnv* jenv);
40 void PyLib_ThrowFNFE(JNIEnv* jenv, const char *file);
41 void PyLib_ThrowUOE(JNIEnv* jenv, const char *message);
42 void PyLib_ThrowRTE(JNIEnv* jenv, const char *message);
43 void PyLib_RedirectStdOut(void);
44 int copyPythonDictToJavaMap(JNIEnv *jenv, PyObject *pyDict, jobject jMap);
45
46 static PyThreadState *_save = NULL;
47
48
49 //#define JPy_JNI_DEBUG 1
50 #define JPy_JNI_DEBUG 0
51
52 // Make sure the following contants are same as in enum org.jpy.PyInputMode
53 #define JPy_IM_STATEMENT 256
54 #define JPy_IM_SCRIPT 257
55 #define JPy_IM_EXPRESSION 258
56
57 #if PY_VERSION_HEX >= 0x030D0000
58 #define JPy_Py_IsFinalizing Py_IsFinalizing
59 #else
60 #define JPy_Py_IsFinalizing _Py_IsFinalizing
61 #endif
62
63 // Checking if Python is in the middle of finalization to make sure that we do not attempt to interact with the Python
64 // runtime while it is shutting down. This helps prevent undefined behavior, such as thread hanging/crashing in
65 // PyGILState_Ensure() as described in https://docs.python.org/3.14/c-api/init.html#c.PyGILState_Ensure. Note that this
66 // approach has some limitations:
67 // 1. it doesn't completely prevent the race condition from happening(TOCTOU), but it mitigates the risk significantly.
68 // 2. it adds some overhead to calling Python from Java, but this is usually negligible compared to the cost of acquiring
69 // and releasing the GIL itself.
70 #define JPy_BEGIN_GIL_STATE(retval) { \
71 if (JPy_Py_IsFinalizing() != 0) { \
72 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Thread attempted to call into Python during interpreter shutdown. Raising exception.\n"); \
73 (*jenv)->ThrowNew(jenv, JPy_RuntimeException_JClass, "Thread attempted to call into Python during interpreter shutdown"); \
74 return (retval); \
75 } \
76 PyGILState_STATE gilState = PyGILState_Ensure();
77
78 #define JPy_BEGIN_GIL_STATE_VOID() { \
79 if (JPy_Py_IsFinalizing() != 0) { \
80 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Thread attempted to call into Python during interpreter shutdown. Raising exception.\n"); \
81 (*jenv)->ThrowNew(jenv, JPy_RuntimeException_JClass, "Thread attempted to call into Python during interpreter shutdown"); \
82 return; \
83 } \
84 PyGILState_STATE gilState = PyGILState_Ensure();
85
86 #define JPy_END_GIL_STATE PyGILState_Release(gilState); }
87
88
89 /**
90 * Called if the JVM loads this module.
91 * Will only called if this module's code is linked into a shared library and loaded by a Java VM.
92 */
93 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* jvm, void* reserved)
94 {
95 if (JPy_JNI_DEBUG) printf("JNI_OnLoad: enter: jvm=%p, JPy_JVM=%p, JPy_MustDestroyJVM=%d, Py_IsInitialized()=%d\n",
96 jvm, JPy_JVM, JPy_MustDestroyJVM, Py_IsInitialized());
97
98 if (JPy_JVM == NULL) {
99 JPy_JVM = jvm;
100 JPy_MustDestroyJVM = JNI_FALSE;
101 } else if (JPy_JVM == jvm) {
102 if (JPy_JNI_DEBUG) printf("JNI_OnLoad: warning: same JVM already running\n");
103 } else {
104 if (JPy_JNI_DEBUG) printf("JNI_OnLoad: warning: different JVM already running (expect weird things!)\n");
105 }
106
107 if (JPy_JNI_DEBUG) printf("JNI_OnLoad: exit: jvm=%p, JPy_JVM=%p, JPy_MustDestroyJVM=%d, Py_IsInitialized()=%d\n",
108 jvm, JPy_JVM, JPy_MustDestroyJVM, Py_IsInitialized());
109
110 if (JPy_JNI_DEBUG) fflush(stdout);
111
112 return JPY_JNI_VERSION;
113 }
114
115
116 /**
117 * Called if the JVM unloads this module.
118 * Will only called if this module's code is linked into a shared library and loaded by a Java VM.
119 */
120 JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* jvm, void* reserved)
121 {
122 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "JNI_OnUnload: enter: jvm=%p, JPy_JVM=%p, JPy_MustDestroyJVM=%d, Py_IsInitialized()=%d\n",
123 jvm, JPy_JVM, JPy_MustDestroyJVM, Py_IsInitialized());
124
125 Py_Finalize();
126
127 if (!JPy_MustDestroyJVM) {
128 JPy_ClearGlobalVars(JPy_GetJNIEnv());
129 JPy_JVM = NULL;
130 }
131
132 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "JNI_OnUnload: exit: jvm=%p, JPy_JVM=%p, JPy_MustDestroyJVM=%d, Py_IsInitialized()=%d\n",
133 jvm, JPy_JVM, JPy_MustDestroyJVM, Py_IsInitialized());
134 }
135
136
137
138 /*
139 * Class: org_jpy_PyLib
140 * Method: isPythonRunning
141 * Signature: ()Z
142 */
143 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_isPythonRunning
144 (JNIEnv* jenv, jclass jLibClass)
145 {
146 int init;
147 init = Py_IsInitialized();
148 return init && JPy_Module != NULL;
149 }
150
151 #define MAX_PYTHON_HOME 256
152 wchar_t staticPythonHome[MAX_PYTHON_HOME];
153
154 /*
155 * Class: org_jpy_PyLib
156 * Method: setPythonHome
157 * Signature: (Ljava/lang/String;)Z
158 */
159 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_setPythonHome
160 (JNIEnv* jenv, jclass jLibClass, jstring jPythonHome)
161 {
162 const wchar_t* pythonHome = NULL;
163
164 const char *nonWidePythonHome = NULL;
165 jboolean result = JNI_FALSE;
166 nonWidePythonHome = (*jenv)->GetStringUTFChars(jenv, jPythonHome, NULL);
167
168 if (nonWidePythonHome != NULL) {
169 pythonHome = Py_DecodeLocale(nonWidePythonHome, NULL);
170 if (pythonHome != NULL) {
171 if (wcslen(pythonHome) < MAX_PYTHON_HOME) {
172 wcscpy(staticPythonHome, pythonHome);
173 result = JNI_TRUE;
174 }
175 else {
176 PyMem_RawFree(pythonHome);
177 }
178 }
179
180 if (result) {
181 Py_SetPythonHome(staticPythonHome);
182 PyMem_RawFree(pythonHome);
183 }
184
185 (*jenv)->ReleaseStringUTFChars(jenv, jPythonHome, nonWidePythonHome);
186 }
187
188 return result;
189 }
190
191 #define MAX_PROGRAM_NAME 256
192 wchar_t staticProgramName[MAX_PROGRAM_NAME];
193
194 /*
195 * Class: org_jpy_PyLib
196 * Method: setProgramName
197 * Signature: (Ljava/lang/String;)Z
198 */
199 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_setProgramName
200 (JNIEnv* jenv, jclass jLibClass, jstring jProgramName)
201 {
202 const wchar_t* programName = NULL;
203
204 const char *nonWideProgramName = NULL;
205 jboolean result = JNI_FALSE;
206 nonWideProgramName = (*jenv)->GetStringUTFChars(jenv, jProgramName, NULL);
207
208 if (nonWideProgramName != NULL) {
209 programName = Py_DecodeLocale(nonWideProgramName, NULL);
210 if (programName != NULL) {
211 if (wcslen(programName) < MAX_PROGRAM_NAME) {
212 wcscpy(staticProgramName, programName);
213 result = JNI_TRUE;
214 }
215 else {
216 PyMem_RawFree(programName);
217 }
218
219 }
220
221 if (result) {
222 Py_SetProgramName(staticProgramName);
223
224 PyMem_RawFree(programName);
225 }
226
227 (*jenv)->ReleaseStringUTFChars(jenv, jProgramName, nonWideProgramName);
228 }
229
230 return result;
231 }
232
233 /*
234 * Class: org_jpy_PyLib
235 * Method: startPython0
236 * Signature: ([Ljava/lang/String;)Z
237 */
238 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_startPython0
239 (JNIEnv* jenv, jclass jLibClass, jobjectArray jPathArray)
240 {
241 int pyInit = Py_IsInitialized();
242
243 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_startPython: entered: jenv=%p, pyInit=%d, JPy_Module=%p\n", jenv, pyInit, JPy_Module);
244
245 if (!pyInit) {
246 Py_Initialize();
247 // See https://github.com/bcdev/jpy/issues/81
248 PySys_SetArgvEx(0, NULL, 0);
249 PyLib_RedirectStdOut();
250 pyInit = Py_IsInitialized(); // todo: assert pyInit == 1?
251
252 PyEval_InitThreads();
253 _save = PyEval_SaveThread(); // todo: assert not null
254 }
255
256 if (pyInit) {
257
258 if (JPy_DiagFlags != 0) {
259 printf("PyLib_startPython: global Python interpreter information:\n");
•260 #if PY_VERSION_HEX < 0x030F0000
261 printf(" Py_GetProgramName() = \"%ls\"\n", Py_GetProgramName());
262 printf(" Py_GetPrefix() = \"%ls\"\n", Py_GetPrefix());
263 printf(" Py_GetExecPrefix() = \"%ls\"\n", Py_GetExecPrefix());
264 printf(" Py_GetProgramFullPath() = \"%ls\"\n", Py_GetProgramFullPath());
265 printf(" Py_GetPath() = \"%ls\"\n", Py_GetPath());
266 printf(" Py_GetPythonHome() = \"%ls\"\n", Py_GetPythonHome());
•267 #endif
268 printf(" Py_GetVersion() = \"%s\"\n", Py_GetVersion());
269 printf(" Py_GetPlatform() = \"%s\"\n", Py_GetPlatform());
270 printf(" Py_GetCompiler() = \"%s\"\n", Py_GetCompiler());
271 printf(" Py_GetBuildInfo() = \"%s\"\n", Py_GetBuildInfo());
272 }
273
274 // If we've got jPathArray, add all entries to Python's "sys.path"
275 //
276 if (jPathArray != NULL) {
277 PyObject* pyPathList;
278 PyObject* pyPath;
279 jstring jPath;
280 jsize i, pathCount;
281
282 pathCount = (*jenv)->GetArrayLength(jenv, jPathArray);
283 //printf(">> pathCount=%d\n", pathCount);
284 if (pathCount > 0) {
285
286 JPy_BEGIN_GIL_STATE(JNI_FALSE)
287
288 pyPathList = PySys_GetObject("path");
289 //printf(">> pyPathList=%p, len=%ld\n", pyPathList, PyList_Size(pyPathList));
290 if (pyPathList != NULL) {
291 JPy_INCREF(pyPathList);
292 for (i = pathCount - 1; i >= 0; i--) {
293 jPath = (*jenv)->GetObjectArrayElement(jenv, jPathArray, i);
294 //printf(">> i=%d, jPath=%p\n", i, jPath);
295 if (jPath != NULL) {
296 pyPath = JPy_FromJString(jenv, jPath);
297 //printf(">> i=%d, pyPath=%p\n", i, pyPath);
298 if (pyPath != NULL) {
299 PyList_Insert(pyPathList, 0, pyPath);
300 }
301 }
302 }
303 JPy_DECREF(pyPathList);
304 }
305 //printf(">> pyPathList=%p, len=%ld\n", pyPathList, PyList_Size(pyPathList));
306 //printf(">> pyPathList=%p, len=%ld (check)\n", PySys_GetObject("path"), PyList_Size(PySys_GetObject("path")));
307
308 JPy_END_GIL_STATE
309 }
310 }
311
312 // if the global JPy_Module is NULL, then the 'jpy' extension module has not been imported yet.
313 //
314 if (JPy_Module == NULL) {
315 PyObject* pyModule;
316
317 JPy_BEGIN_GIL_STATE(JNI_FALSE)
318
319 // We import 'jpy' so that Python can call our PyInit_jpy() which sets up a number of
320 // required global variables (including JPy_Module, see above).
321 //
322 pyModule = PyImport_ImportModule("jpy");
323 //printf(">> pyModule=%p\n", pyModule);
324 if (pyModule == NULL) {
325 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_startPython: failed to import module 'jpy'\n");
326 if (JPy_DiagFlags != 0 && PyErr_Occurred()) {
327 PyErr_Print();
328 }
329 PyLib_HandlePythonException(jenv);
330 }
331
332 JPy_END_GIL_STATE
333 }
334 }
335
336 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_startPython: exiting: jenv=%p, pyInit=%d, JPy_Module=%p\n", jenv, pyInit, JPy_Module);
337
338 //printf(">> JPy_Module=%p\n", JPy_Module);
339
340 if (!pyInit) {
341 (*jenv)->ThrowNew(jenv, JPy_RuntimeException_JClass, "Failed to initialize Python interpreter.");
342 return JNI_FALSE;
343 }
344 if (JPy_Module == NULL) {
345 (*jenv)->ThrowNew(jenv, JPy_RuntimeException_JClass, "Failed to initialize Python 'jpy' module.");
346 return JNI_FALSE;
347 }
348 return JNI_TRUE;
349 }
350
351 /*
352 * Class: org_jpy_PyLib
353 * Method: stopPython0
354 * Signature: ()V
355 */
356 JNIEXPORT void JNICALL Java_org_jpy_PyLib_stopPython0
357 (JNIEnv* jenv, jclass jLibClass)
358 {
359 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_stopPython: entered: JPy_Module=%p\n", JPy_Module);
360
361 if (Py_IsInitialized()) {
362 // Cleanup the JPY stateful structures and shut down the interpreter.
363
364 JPy_BEGIN_GIL_STATE_VOID()
365
366 JPy_free();
367
368 JPy_END_GIL_STATE
369
370 PyEval_RestoreThread(_save);
371 _save = NULL;
372 Py_Finalize();
373 }
374
375 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_stopPython: exiting: JPy_Module=%p\n", JPy_Module);
376 }
377
378
379 /*
380 * Class: org_jpy_PyLib
381 * Method: getPythonVersion
382 * Signature: ()Ljava/lang/String;
383 */
384 JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_getPythonVersion
385 (JNIEnv* jenv, jclass jLibClass)
386 {
387 const char* version;
388
389 version = Py_GetVersion();
390 if (version == NULL) {
391 return NULL;
392 }
393
394 return (*jenv)->NewStringUTF(jenv, version);
395 }
396
397
398 /*
399 * Class: org_jpy_python_PyLib
400 * Method: execScript
401 * Signature: (Ljava/lang/String;)J
402 */
403 JNIEXPORT jint JNICALL Java_org_jpy_PyLib_execScript
404 (JNIEnv* jenv, jclass jLibClass, jstring jScript)
405 {
406 const char* scriptChars;
407 int retCode = -1;
408
409 JPy_BEGIN_GIL_STATE(-1)
410
411 scriptChars = (*jenv)->GetStringUTFChars(jenv, jScript, NULL);
412 if (scriptChars == NULL) {
413 PyLib_ThrowOOM(jenv);
414 goto error;
415 }
416 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_execScript: script='%s'\n", scriptChars);
417 retCode = PyRun_SimpleString(scriptChars);
418 if (retCode < 0) {
419 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_execScript: error: PyRun_SimpleString(\"%s\") returned %d\n", scriptChars, retCode);
420 // Note that we cannot retrieve last Python exception after a calling PyRun_SimpleString, see documentation of PyRun_SimpleString.
421 }
422
423 error:
424 if (scriptChars != NULL) {
425 (*jenv)->ReleaseStringUTFChars(jenv, jScript, scriptChars);
426 }
427
428 JPy_END_GIL_STATE
429
430 return retCode;
431 }
432
433
434 PyObject* PyLib_ConvertJavaToPythonObject(JNIEnv* jenv, jobject jObject)
435 {
436 JPy_JType* type;
437 if (jObject == NULL) {
438 return JPy_FROM_JNULL();
439 }
440 type = JType_GetTypeForObject(jenv, jObject, JNI_FALSE);
441 return JType_ConvertJavaToPythonObject(jenv, type, jObject);
442 }
443
444 int PyLib_ConvertPythonToJavaObject(JNIEnv* jenv, PyObject* pyObject, jobject* jObject)
445 {
446 return JType_ConvertPythonToJavaObject(jenv, JPy_JPyObject, pyObject, jObject, JNI_FALSE);
447 }
448
449 void dumpDict(const char* dictName, PyObject* dict)
450 {
451 Py_ssize_t size;
452 PyObject *key = NULL, *value = NULL;
453 Py_ssize_t pos = 0;
454 Py_ssize_t i = 0;
455
456 if (!PyDict_Check(dict)) {
457 printf(">> dumpDict: %s is not a dictionary!\n", dictName);
458 return;
459 }
460
461 size = PyDict_Size(dict);
462 printf(">> dumpDict: %s.size = %ld\n", dictName, size);
463 #if PY_VERSION_HEX >= 0x030D0000 // >=3.13
464 // PyDict_Next is not thread-safe, so we need to protect it with a critical section
465 // https://docs.python.org/3/howto/free-threading-extensions.html#pydict-next
466 Py_BEGIN_CRITICAL_SECTION(dict);
467 #endif
468 while (PyDict_Next(dict, &pos, &key, &value)) {
469 const char* name;
470 name = JPy_AS_UTF8(key);
471 printf(">> dumpDict: %s[%ld].name = '%s'\n", dictName, i, name);
472 i++;
473 }
474 #if PY_VERSION_HEX >= 0x030D0000 // >=3.13
475 Py_END_CRITICAL_SECTION();
476 #endif
477 }
478
479 /**
480 * Get the globals from the __main__ module.
481 */
482 PyObject *getMainGlobals() {
483 PyObject* pyMainModule;
484 PyObject* pyGlobals;
485
486 pyMainModule = PyImport_AddModule("__main__"); // borrowed ref
487
488 if (pyMainModule == NULL) {
489 return NULL;
490 }
491
492 pyGlobals = PyModule_GetDict(pyMainModule); // borrowed ref
493 JPy_XINCREF(pyGlobals);
494
495 return pyGlobals;
496 }
497
498 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getMainGlobals
499 (JNIEnv *jenv, jclass libClass) {
500 jobject objectRef = NULL;
501 PyObject *globals;
502
503 JPy_BEGIN_GIL_STATE(NULL)
504
505 globals = getMainGlobals(); // new ref
506 if (globals == NULL) {
507 goto error;
508 }
509
510 if (JType_ConvertPythonToJavaObject(jenv, JPy_JPyObject, globals, &objectRef, JNI_FALSE) < 0) {
511 objectRef = NULL;
512 goto error;
513 }
514
515 error:
516 JPy_XDECREF(globals);
517 JPy_END_GIL_STATE
518
519 return objectRef;
520 }
521
522 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getCurrentGlobals
523 (JNIEnv *jenv, jclass libClass) {
524 jobject objectRef = NULL;
525 PyObject *globals;
526
527 JPy_BEGIN_GIL_STATE(NULL)
528
529 #if PY_VERSION_HEX < 0x030D0000 // < 3.13
530 globals = PyEval_GetGlobals(); // borrowed ref
531 JPy_XINCREF(globals);
532 #else
533 // See https://peps.python.org/pep-0667 for the change in Python 3.13
534 globals = PyEval_GetFrameGlobals(); // new ref
535 #endif
536
537 if (globals == NULL) {
538 goto error;
539 }
540
541 if (JType_ConvertPythonToJavaObject(jenv, JPy_JPyObject, globals, &objectRef, JNI_FALSE) < 0) {
542 objectRef = NULL;
543 goto error;
544 }
545
546 error:
547 JPy_XDECREF(globals);
548 JPy_END_GIL_STATE
549
550 return objectRef;
551 }
552
553 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getCurrentLocals
554 (JNIEnv *jenv, jclass libClass) {
555 jobject objectRef = NULL;
556 PyObject *locals;
557
558 JPy_BEGIN_GIL_STATE(NULL)
559
560 #if PY_VERSION_HEX < 0x030D0000 // < 3.13
561 locals = PyEval_GetLocals(); // borrowed ref
562 JPy_XINCREF(locals);
563 #else
564 // See https://peps.python.org/pep-0667 for the change in Python 3.13
565 locals = PyEval_GetFrameLocals(); // new ref
566 #endif
567
568 if (locals == NULL) {
569 goto error;
570 }
571
572 if (JType_ConvertPythonToJavaObject(jenv, JPy_JPyObject, locals, &objectRef, JNI_FALSE) < 0) {
573 objectRef = NULL;
574 goto error;
575 }
576
577 error:
578 JPy_XDECREF(locals);
579 JPy_END_GIL_STATE
580
581 return objectRef;
582 }
583
584
585 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_copyDict
586 (JNIEnv *jenv, jclass libClass, jlong pyPointer) {
587 jobject objectRef = NULL;
588 PyObject* copy = NULL;
589 PyObject* src = (PyObject*)pyPointer;
590
591 JPy_BEGIN_GIL_STATE(NULL)
592
593 if (!PyDict_Check(src)) {
594 PyLib_ThrowUOE(jenv, "Not a dictionary!");
595 goto error;
596 }
597
598 copy = PyDict_Copy(src);
599 if (JType_ConvertPythonToJavaObject(jenv, JPy_JPyObject, copy, &objectRef, JNI_FALSE) < 0) {
600 objectRef = NULL;
601 goto error;
602 }
603
604 error:
605 JPy_XDECREF(copy);
606 JPy_END_GIL_STATE
607
608 return objectRef;
609 }
610
611 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_newDict
612 (JNIEnv *jenv, jclass libClass) {
613 jobject objectRef = NULL;
614 PyObject *dict;
615
616 JPy_BEGIN_GIL_STATE(NULL)
617
618 dict = PyDict_New();
619
620 if (JType_ConvertPythonToJavaObject(jenv, JPy_JPyObject, dict, &objectRef, JNI_FALSE) < 0) {
621 objectRef = NULL;
622 goto error;
623 }
624
625 error:
626 JPy_XDECREF(dict);
627 JPy_END_GIL_STATE
628
629 return objectRef;
630 }
631
632 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_pyDictKeys
633 (JNIEnv *jenv, jclass libClass, jlong pyDict) {
634 jobject result = NULL;
635 PyObject* keys = NULL;
636 PyObject* src = (PyObject*)pyDict;
637
638 JPy_BEGIN_GIL_STATE(NULL)
639
640 if (!PyDict_Check(src)) {
641 PyLib_ThrowUOE(jenv, "Not a dictionary!");
642 goto error;
643 }
644
645 keys = PyDict_Keys(src);
646 if (JType_CreateJavaPyObject(jenv, JPy_JPyObject, keys, &result) < 0) {
647 result = NULL;
648 goto error;
649 }
650
651 error:
652 JPy_XDECREF(keys);
653 JPy_END_GIL_STATE
654 return result;
655 }
656
657 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_pyDictValues
658 (JNIEnv *jenv, jclass libClass, jlong pyDict) {
659 jobject result = NULL;
660 PyObject* values = NULL;
661 PyObject* src = (PyObject*)pyDict;
662
663 JPy_BEGIN_GIL_STATE(NULL)
664
665 if (!PyDict_Check(src)) {
666 PyLib_ThrowUOE(jenv, "Not a dictionary!");
667 goto error;
668 }
669
670 values = PyDict_Values(src);
671 if (JType_CreateJavaPyObject(jenv, JPy_JPyObject, values, &result) < 0) {
672 result = NULL;
673 goto error;
674 }
675
676 error:
677 JPy_XDECREF(values);
678 JPy_END_GIL_STATE
679 return result;
680 }
681
682 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyDictContains
683 (JNIEnv *jenv, jclass libClass, jlong pyDict, jobject jKey, jclass jKeyClass) {
684 PyObject* src = (PyObject*)pyDict;
685 int result = 0;
686 JPy_JType* keyType;
687 PyObject* pyKey;
688
689 JPy_BEGIN_GIL_STATE(JNI_FALSE)
690
691 if (!PyDict_Check(src)) {
692 result = -1;
693 PyLib_ThrowUOE(jenv, "Not a dictionary!");
694 goto error;
695 }
696
697 if (jKeyClass != NULL) {
698 keyType = JType_GetType(jenv, jKeyClass, JNI_FALSE);
699 if (keyType == NULL) {
700 result = -1;
701 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_pyDictContains: failed to retrieve type\n");
702 PyLib_HandlePythonException(jenv);
703 goto error;
704 }
705 pyKey = JPy_FromJObjectWithType(jenv, jKey, keyType);
706 } else {
707 pyKey = JPy_FromJObject(jenv, jKey);
708 }
709
710 result = PyDict_Contains(src, pyKey);
711 if (result < 0) {
712 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_pyDictContains: PyDict_Contains error\n");
713 PyLib_HandlePythonException(jenv);
714 goto error;
715 }
716
717 error:
718 JPy_END_GIL_STATE
719 return result == 1 ? JNI_TRUE : JNI_FALSE;
720 }
721
722 /**
723 * Copies a Java Map<String, Object> into a new Python dictionary.
724 */
725 PyObject *copyJavaStringObjectMapToPyDict(JNIEnv *jenv, jobject jMap) {
726 PyObject* result = NULL;
727 jobject entrySet, iterator, mapEntry;
728 jboolean hasNext;
729
730 result = PyDict_New();
731 if (result == NULL) {
732 return result;
733 }
734
735 entrySet = (*jenv)->CallObjectMethod(jenv, jMap, JPy_Map_entrySet_MID);
736 if (entrySet == NULL) {
737 goto error;
738 }
739
740 iterator = (*jenv)->CallObjectMethod(jenv, entrySet, JPy_Set_Iterator_MID);
741 if (iterator == NULL) {
742 goto error;
743 }
744
745 hasNext = (*jenv)->CallBooleanMethod(jenv, iterator, JPy_Iterator_hasNext_MID);
746
747 while (hasNext) {
748 jobject key, value;
749 char const *keyChars;
750 PyObject *pyKey;
751 PyObject *pyValue;
752 JPy_JType* type;
753
754 mapEntry = (*jenv)->CallObjectMethod(jenv, iterator, JPy_Iterator_next_MID);
755 if (mapEntry == NULL) {
756 goto error;
757 }
758
759 key = (*jenv)->CallObjectMethod(jenv, mapEntry, JPy_Map_Entry_getKey_MID);
760 if (key == NULL) {
761 goto error;
762 }
763
764 // we require string keys
765 if (!(*jenv)->IsInstanceOf(jenv, key, JPy_String_JClass)) {
766 goto error;
767 }
768 keyChars = (*jenv)->GetStringUTFChars(jenv, (jstring)key, NULL);
769 if (keyChars == NULL) {
770 goto error;
771 }
772
773 pyKey = JPy_FROM_CSTR(keyChars);
774 (*jenv)->ReleaseStringUTFChars(jenv, (jstring)key, keyChars);
775
776 value = (*jenv)->CallObjectMethod(jenv, mapEntry, JPy_Map_Entry_getValue_MID);
777
778 type = JType_GetTypeForObject(jenv, value, JNI_FALSE);
779 pyValue = JType_ConvertJavaToPythonObject(jenv, type, value);
780
781 PyDict_SetItem(result, pyKey, pyValue);
782
783 hasNext = (*jenv)->CallBooleanMethod(jenv, iterator, JPy_Iterator_hasNext_MID);
784 }
785
786 return result;
787
788 error:
789 JPy_XDECREF(result);
790 return NULL;
791 }
792
793 int copyPythonDictToJavaMap(JNIEnv *jenv, PyObject *pyDict, jobject jMap) {
794 PyObject *pyKey, *pyValue;
795 Py_ssize_t pos = 0;
796 Py_ssize_t dictSize;
797 jobject *jValues = NULL;
798 jobject *jKeys = NULL;
799 int ii;
800 jboolean exceptionAlready = JNI_FALSE;
801 jthrowable savedException = NULL;
802 int retcode = -1;
803
804 if (!PyDict_Check(pyDict)) {
805 PyLib_ThrowUOE(jenv, "PyObject is not a dictionary!");
806 return -1;
807 }
808
809 dictSize = PyDict_Size(pyDict);
810
811 jKeys = malloc(dictSize * sizeof(jobject));
812 jValues = malloc(dictSize * sizeof(jobject));
813 if (jKeys == NULL || jValues == NULL) {
814 PyLib_ThrowOOM(jenv);
815 goto error;
816 }
817
818 exceptionAlready = (*jenv)->ExceptionCheck(jenv);
819 if (exceptionAlready) {
820 // save the exception away, because otherwise the conversion methods might spuriously fail
821 savedException = (*jenv)->ExceptionOccurred(jenv);
822 (*jenv)->ExceptionClear(jenv);
823 }
824
825 // first convert everything
826 ii = 0;
827 while (PyDict_Next(pyDict, &pos, &pyKey, &pyValue)) {
828 if (JPy_AsJObjectWithClass(jenv, pyKey, &(jKeys[ii]), JPy_String_JClass) < 0) {
829 // an error occurred
830 goto error;
831 }
832 if (JPy_AsJObject(jenv, pyValue, &(jValues[ii]), JNI_TRUE) < 0) {
833 // an error occurred
834 goto error;
835 }
836 ii++;
837 }
838
839 // now that we've converted, clear out the map and repopulate it
840 (*jenv)->CallVoidMethod(jenv, jMap, JPy_Map_clear_MID);
841 for (ii = 0; ii < dictSize; ++ii) {
842 // since the map is cleared, we want to plow through all of the put operations
843 (*jenv)->CallObjectMethod(jenv, jMap, JPy_Map_put_MID, jKeys[ii], jValues[ii]);
844 }
845 // and we are successful!
846 retcode = 0;
847
848 error:
849 if (exceptionAlready) {
850 // restore our original exception
851 (*jenv)->Throw(jenv, savedException);
852 }
853
854 free(jKeys);
855 free(jValues);
856 return retcode;
857 }
858
859 typedef PyObject * (*DoRun)(const void *,int,PyObject*,PyObject*);
860
861 /**
862 * After setting up the globals and locals, calls the provided function.
863 *
864 * jStart must be JPy_IM_STATEMENT, JPy_IM_SCRIPT, JPy_IM_EXPRESSION; matching what you are trying to
865 * run. If you use a statement or expression instead of a script; some of your code may be ignored.
866 *
867 * If jGlobals is not specified, then the main module globals are used.
868 *
869 * If jLocals is not specified, then the globals are used.
870 *
871 * jGlobals and jLocals may be a PyObject, in which case they are used without translation. Otherwise,
872 * they must be a map from String to Object, and will be copied to a new python dictionary. After execution
873 * completes the dictionary entries will be copied back.
874 *
875 */
876 jlong executeInternal(JNIEnv* jenv, jclass jLibClass, jint jStart, jobject jGlobals, jobject jLocals, DoRun runFunction, void *runArg) {
877 PyObject *pyReturnValue;
878 PyObject *pyGlobals;
879 PyObject *pyLocals;
880 int start;
881 jboolean decGlobals, decLocals, copyGlobals, copyLocals;
882
883 JPy_BEGIN_GIL_STATE(0)
884
885 decGlobals = decLocals = JNI_FALSE;
886 copyGlobals = copyLocals = JNI_FALSE;
887 pyGlobals = NULL;
888 pyLocals = NULL;
889 pyReturnValue = NULL;
890
891 if (jGlobals == NULL) {
892 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using main globals\n");
893 pyGlobals = getMainGlobals(); // new ref
894 decGlobals = JNI_TRUE;
895 if (pyGlobals == NULL) {
896 PyLib_HandlePythonException(jenv);
897 goto error;
898 }
899 } else if ((*jenv)->IsInstanceOf(jenv, jGlobals, JPy_PyObject_JClass)) {
900 // if we are an instance of PyObject, just use the object
901 pyGlobals = (PyObject *)((*jenv)->CallLongMethod(jenv, jGlobals, JPy_PyObject_GetPointer_MID));
902 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using PyObject globals\n");
903 } else if ((*jenv)->IsInstanceOf(jenv, jGlobals, JPy_PyDictWrapper_JClass)) {
904 // if we are an instance of a wrapped dictionary, just use the underlying dictionary
905 pyGlobals = (PyObject *)((*jenv)->CallLongMethod(jenv, jGlobals, JPy_PyDictWrapper_GetPointer_MID));
906 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using PyDictWrapper globals\n");
907 } else if ((*jenv)->IsInstanceOf(jenv, jGlobals, JPy_Map_JClass)) {
908 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using Java Map globals\n");
909 // this is a java Map and we need to convert it
910 pyGlobals = copyJavaStringObjectMapToPyDict(jenv, jGlobals);
911 if (pyGlobals == NULL) {
912 PyLib_ThrowRTE(jenv, "Could not convert globals from Java Map to Python dictionary");
913 goto error;
914 }
915 copyGlobals = decGlobals = JNI_TRUE;
916 } else {
917 PyLib_ThrowUOE(jenv, "Unsupported globals type");
918 goto error;
919 }
920
921 // if we have no locals specified, using globals for it matches the behavior of eval, "The expression argument is
922 // parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and
923 // locals dictionaries as global and local namespace. ... If the locals dictionary is omitted it defaults to the
924 // globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval()
925 // is called. The return value is the result of the evaluated expression.
926 if (jLocals == NULL) {
927 pyLocals = pyGlobals;
928 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using globals for locals\n");
929 } else if ((*jenv)->IsInstanceOf(jenv, jLocals, JPy_PyObject_JClass)) {
930 // if we are an instance of PyObject, just use the object
931 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using PyObject locals\n");
932 pyLocals = (PyObject *)((*jenv)->CallLongMethod(jenv, jLocals, JPy_PyObject_GetPointer_MID));
933 } else if ((*jenv)->IsInstanceOf(jenv, jLocals, JPy_PyDictWrapper_JClass)) {
934 // if we are an instance of a wrapped dictionary, just use the underlying dictionary
935 pyLocals = (PyObject *)((*jenv)->CallLongMethod(jenv, jLocals, JPy_PyDictWrapper_GetPointer_MID));
936 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using PyDictWrapper locals\n");
937 } else if ((*jenv)->IsInstanceOf(jenv, jLocals, JPy_Map_JClass)) {
938 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: using Java Map locals\n");
939 // this is a java Map and we need to convert it
940 pyLocals = copyJavaStringObjectMapToPyDict(jenv, jLocals);
941 if (pyLocals == NULL) {
942 PyLib_ThrowRTE(jenv, "Could not convert locals from Java Map to Python dictionary");
943 goto error;
944 }
945 copyLocals = decLocals = JNI_TRUE;
946 } else {
947 PyLib_ThrowUOE(jenv, "Unsupported locals type");
948 goto error;
949 }
950
951 start = jStart == JPy_IM_STATEMENT ? Py_single_input :
952 jStart == JPy_IM_SCRIPT ? Py_file_input :
953 Py_eval_input;
954
955 pyReturnValue = runFunction(runArg, start, pyGlobals, pyLocals);
956 if (pyReturnValue == NULL) {
957 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: Handle Python Exception\n");
958 PyLib_HandlePythonException(jenv);
959 goto error;
960 }
961
962 error:
963 if (copyGlobals) {
964 copyPythonDictToJavaMap(jenv, pyGlobals, jGlobals);
965 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: copied back Java global\n");
966 }
967 if (copyLocals) {
968 copyPythonDictToJavaMap(jenv, pyLocals, jLocals);
969 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeInternal: copied back Java locals\n");
970 }
971 if (decGlobals) {
972 JPy_XDECREF(pyGlobals);
973 }
974 if (decLocals) {
975 JPy_XDECREF(pyLocals);
976 }
977
978 JPy_END_GIL_STATE
979
980 return (jlong) pyReturnValue;
981 }
982
983 PyObject *pyRunStringWrapper(const char *code, int start, PyObject *globals, PyObject *locals) {
984 PyObject *result = PyRun_String(code, start, globals, locals);
985 return result;
986 }
987
988 /**
989 * Calls PyRun_String under the covers to execute the string contents.
990 *
991 * jStart must be JPy_IM_STATEMENT, JPy_IM_SCRIPT, JPy_IM_EXPRESSION; matching what you are trying to
992 * run. If you use a statement or expression instead of a script; some of your code may be ignored.
993 *
994 * If jGlobals is not specified, then the main module globals are used.
995 *
996 * If jLocals is not specified, then the globals are used.
997 *
998 * jGlobals and jLocals may be a PyObject, in which case they are used without translation. Otherwise,
999 * they must be a map from String to Object, and will be copied to a new python dictionary. After execution
1000 * completes the dictionary entries will be copied back.
1001 */
1002 JNIEXPORT
1003 jlong JNICALL Java_org_jpy_PyLib_executeCode
1004 (JNIEnv* jenv, jclass jLibClass, jstring jCode, jint jStart, jobject jGlobals, jobject jLocals) {
1005 const char *codeChars;
1006 jlong result;
1007
1008 codeChars = (*jenv)->GetStringUTFChars(jenv, jCode, NULL);
1009 if (codeChars == NULL) {
1010 PyLib_ThrowOOM(jenv);
1011 return 0;
1012 }
1013
1014 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_executeCode: code='%s'\n", codeChars);
1015
1016 result = executeInternal(jenv, jLibClass, jStart, jGlobals, jLocals, (DoRun)pyRunStringWrapper, codeChars);
1017
1018 if (codeChars != NULL) {
1019 (*jenv)->ReleaseStringUTFChars(jenv, jCode, codeChars);
1020 }
1021
1022 return result;
1023 }
1024
1025 typedef struct {
1026 FILE *fp;
1027 const char *filechars;
1028 } RunFileArgs;
1029
1030 PyObject *pyRunFileWrapper(RunFileArgs *args, int start, PyObject *globals, PyObject *locals) {
1031 return PyRun_File(args->fp, args->filechars, start, globals, locals);
1032 }
1033
1034 /**
1035 * Calls PyRun_Script under the covers to execute the script contents.
1036 *
1037 * jStart must be JPy_IM_STATEMENT, JPy_IM_SCRIPT, JPy_IM_EXPRESSION; matching what you are trying to
1038 * run. If you use a statement or expression instead of a script; some of your code may be ignored.
1039 *
1040 * If jGlobals is not specified, then the main module globals are used.
1041 *
1042 * If jLocals is not specified, then the globals are used.
1043 *
1044 * jGlobals and jLocals may be a PyObject, in which case they are used without translation. Otherwise,
1045 * they must be a map from String to Object, and will be copied to a new python dictionary. After execution
1046 * completes the dictionary entries will be copied back.
1047 */
1048 JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_executeScript
1049 (JNIEnv* jenv, jclass jLibClass, jstring jFile, jint jStart, jobject jGlobals, jobject jLocals) {
1050 RunFileArgs runFileArgs;
1051 jlong result = 0;
1052
1053 runFileArgs.fp = NULL;
1054 runFileArgs.filechars = NULL;
1055
1056 runFileArgs.filechars = (*jenv)->GetStringUTFChars(jenv, jFile, NULL);
1057 if (runFileArgs.filechars == NULL) {
1058 PyLib_ThrowOOM(jenv);
1059 goto error;
1060 }
1061
1062 runFileArgs.fp = fopen(runFileArgs.filechars, "r");
1063 if (!runFileArgs.fp) {
1064 PyLib_ThrowFNFE(jenv, runFileArgs.filechars);
1065 goto error;
1066 }
1067
1068 result = executeInternal(jenv, jLibClass, jStart, jGlobals, jLocals, (DoRun)pyRunFileWrapper, &runFileArgs);
1069
1070 error:
1071 if (runFileArgs.filechars != NULL) {
1072 (*jenv)->ReleaseStringUTFChars(jenv, jFile, runFileArgs.filechars);
1073 }
1074 if (runFileArgs.fp != NULL) {
1075 fclose(runFileArgs.fp);
1076 }
1077 return result;
1078 }
1079
1080 /*
1081 * Class: org_jpy_python_PyLib
1082 * Method: incRef
1083 * Signature: (J)V
1084 */
1085 JNIEXPORT void JNICALL Java_org_jpy_PyLib_incRef
1086 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1087 {
1088 PyObject* pyObject;
1089 Py_ssize_t refCount;
1090
1091 pyObject = (PyObject*) objId;
1092
1093 if (Py_IsInitialized()) {
1094 JPy_BEGIN_GIL_STATE_VOID()
1095
1096 refCount = Py_REFCNT(pyObject);
1097 JPy_DIAG_PRINT(JPy_DIAG_F_MEM, "Java_org_jpy_PyLib_incRef: pyObject=%p, refCount=%d, type='%s'\n", pyObject, refCount, Py_TYPE(pyObject)->tp_name);
1098 JPy_INCREF(pyObject);
1099
1100 JPy_END_GIL_STATE
1101 } else {
1102 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_incRef: error: no interpreter: pyObject=%p\n", pyObject);
1103 }
1104 }
1105
1106 /*
1107 * Class: org_jpy_python_PyLib
1108 * Method: decRef
1109 * Signature: (J)V
1110 */
1111 JNIEXPORT void JNICALL Java_org_jpy_PyLib_decRef
1112 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1113 {
1114 PyObject* pyObject;
1115 Py_ssize_t refCount;
1116
1117 pyObject = (PyObject*) objId;
1118
1119 if (Py_IsInitialized()) {
1120 JPy_BEGIN_GIL_STATE_VOID()
1121
1122 refCount = Py_REFCNT(pyObject);
1123 if (refCount <= 0) {
1124 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_decRef: error: refCount <= 0: pyObject=%p, refCount=%d\n", pyObject, refCount);
1125 } else {
1126 JPy_DIAG_PRINT(JPy_DIAG_F_MEM, "Java_org_jpy_PyLib_decRef: pyObject=%p, refCount=%d, type='%s'\n", pyObject, refCount, Py_TYPE(pyObject)->tp_name);
1127 JPy_DECREF(pyObject);
1128 }
1129
1130 JPy_END_GIL_STATE
1131 } else {
1132 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_decRef: error: no interpreter: pyObject=%p\n", pyObject);
1133 }
1134 }
1135
1136 JNIEXPORT void JNICALL Java_org_jpy_PyLib_decRefs
1137 (JNIEnv* jenv, jclass jLibClass, jlongArray objIds, jsize len)
1138 {
1139 PyObject* pyObject;
1140 Py_ssize_t refCount;
1141 jsize i;
1142
1143 jboolean isCopy;
1144 jlong* buf;
1145
1146 if (Py_IsInitialized()) {
1147 JPy_BEGIN_GIL_STATE_VOID()
1148
1149 // Note: it *may* be desirable to instead force a local copy using GetLongArrayRegion, TBD.
1150 // It is *not* a good idea to use a critical array here, as JPy_DECREF may trigger the python
1151 // object destructor, which can run arbitrary code.
1152 buf = (*jenv)->GetLongArrayElements(jenv, objIds, &isCopy);
1153 for (i = 0; i < len; i++) {
1154 pyObject = (PyObject*) buf[i];
1155 refCount = Py_REFCNT(pyObject);
1156 if (refCount <= 0) {
1157 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_decRefs: error: refCount <= 0: pyObject=%p, refCount=%d\n", pyObject, refCount);
1158 } else {
1159 JPy_DIAG_PRINT(JPy_DIAG_F_MEM, "Java_org_jpy_PyLib_decRefs: pyObject=%p, refCount=%d, type='%s'\n", pyObject, refCount, Py_TYPE(pyObject)->tp_name);
1160 JPy_DECREF(pyObject);
1161 }
1162 }
1163 (*jenv)->ReleaseLongArrayElements(jenv, objIds, buf, JNI_ABORT);
1164 JPy_END_GIL_STATE
1165 } else {
1166 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_decRefs: error: no interpreter\n");
1167 }
1168 }
1169
1170
1171 /*
1172 * Class: org_jpy_python_PyLib
1173 * Method: getIntValue
1174 * Signature: (J)I
1175 */
1176 JNIEXPORT jint JNICALL Java_org_jpy_PyLib_getIntValue
1177 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1178 {
1179 PyObject* pyObject;
1180 jint value;
1181
1182 JPy_BEGIN_GIL_STATE(-1)
1183
1184 pyObject = (PyObject*) objId;
1185 value = (jint) JPy_AS_CLONG(pyObject);
1186 // Note: we are not handling the overflow case, but there might be a need to have getIntValueSafe() in the future
1187 if (value == -1 && PyErr_Occurred()) {
1188 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_getIntValue: error: failed to convert Python object to Java int\n");
1189 PyLib_HandlePythonException(jenv);
1190 }
1191
1192 JPy_END_GIL_STATE
1193
1194 return value;
1195 }
1196
1197 /*
1198 * Class: org_jpy_python_PyLib
1199 * Method: getLongValue
1200 * Signature: (J)J
1201 */
1202 JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_getLongValue
1203 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1204 {
1205 PyObject* pyObject;
1206 jlong value;
1207
1208 JPy_BEGIN_GIL_STATE(-1)
1209
1210 pyObject = (PyObject*) objId;
1211 value = JPy_AS_CLONG(pyObject);
1212 if (value == -1 && PyErr_Occurred()) {
1213 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_getLongValue: error: failed to convert Python object to Java long\n");
1214 PyLib_HandlePythonException(jenv);
1215 }
1216 JPy_END_GIL_STATE
1217
1218 return value;
1219 }
1220
1221 /**
1222 * Used to convert a python object into it's corresponding boolean. If the PyObject is not a boolean;
1223 * then return false.
1224 */
1225 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_getBooleanValue
1226 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1227 {
1228 PyObject* pyObject;
1229 jboolean value;
1230
1231 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1232
1233 pyObject = (PyObject*) objId;
1234 if (PyBool_Check(pyObject)) {
1235 value = (pyObject == Py_True) ? JNI_TRUE : JNI_FALSE;
1236 } else {
1237 value = JNI_FALSE;
1238 }
1239
1240 JPy_END_GIL_STATE
1241
1242 return value;
1243 }
1244
1245 /*
1246 * Class: org_jpy_python_PyLib
1247 * Method: getDoubleValue
1248 * Signature: (J)D
1249 */
1250 JNIEXPORT jdouble JNICALL Java_org_jpy_PyLib_getDoubleValue
1251 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1252 {
1253 PyObject* pyObject;
1254 jdouble value;
1255
1256 JPy_BEGIN_GIL_STATE(-1.0)
1257
1258 pyObject = (PyObject*) objId;
1259 value = (jdouble) PyFloat_AsDouble(pyObject);
1260 if (value == -1.0 && PyErr_Occurred()) {
1261 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_getDoubleValue: error: failed to convert Python object to Java double\n");
1262 PyLib_HandlePythonException(jenv);
1263 }
1264
1265 JPy_END_GIL_STATE
1266
1267 return value;
1268 }
1269
1270 /*
1271 * Class: org_jpy_python_PyLib
1272 * Method: getStringValue
1273 * Signature: (J)Ljava/lang/String;
1274 */
1275 JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_getStringValue
1276 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1277 {
1278 PyObject* pyObject;
1279 jstring jString;
1280
1281 JPy_BEGIN_GIL_STATE(NULL)
1282
1283 pyObject = (PyObject*) objId;
1284
1285 if (JPy_AsJString(jenv, pyObject, &jString) < 0) {
1286 jString = NULL;
1287 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_getStringValue: error: failed to convert Python object to Java String\n");
1288 PyLib_HandlePythonException(jenv);
1289 }
1290
1291 JPy_END_GIL_STATE
1292
1293 return jString;
1294 }
1295
1296 /*
1297 * Class: org_jpy_python_PyLib
1298 * Method: getObjectValue
1299 * Signature: (J)Ljava/lang/Object;
1300 */
1301 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getObjectValue
1302 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1303 {
1304 PyObject* pyObject;
1305 jobject jObject;
1306
1307 JPy_BEGIN_GIL_STATE(NULL)
1308
1309 pyObject = (PyObject*) objId;
1310
1311 if (JObj_Check(pyObject)) {
1312 jObject = ((JPy_JObj*) pyObject)->objectRef;
1313 } else {
1314 if (JPy_AsJObject(jenv, pyObject, &jObject, JNI_FALSE) < 0) {
1315 jObject = NULL;
1316 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_getObjectValue: error: failed to convert Python object to Java Object\n");
1317 PyLib_HandlePythonException(jenv);
1318 }
1319 }
1320
1321 JPy_END_GIL_STATE
1322
1323 return jObject;
1324 }
1325
1326 /**
1327 * Returns true if this object can be converted from a Python object into a Java object (or primitive);
1328 * if this returns false, when you fetch an Object from Python it will be a PyObject wrapper.
1329 *
1330 * objId is a pointer to a PyObject.
1331 */
1332 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_isConvertible
1333 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1334 {
1335 PyObject* pyObject;
1336 jboolean result;
1337
1338 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1339
1340 pyObject = (PyObject*) objId;
1341
1342 result = pyObject == Py_None || JObj_Check(pyObject) || PyBool_Check(pyObject) ||
1343 JPy_IS_CLONG(pyObject) || PyFloat_Check(pyObject) || JPy_IS_STR(pyObject) ? JNI_TRUE : JNI_FALSE;
1344
1345
1346 JPy_END_GIL_STATE
1347
1348 return result;
1349 }
1350
1351 /**
1352 * Gets the Python type object of specified objId.
1353 *
1354 * objId is a pointer to a PyObject.
1355 */
1356 JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_getType
1357 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1358 {
1359 PyObject* pyObject;
1360
1361 JPy_BEGIN_GIL_STATE(0)
1362
•1363 pyObject = (PyObject*) ((PyObject*) objId)->ob_type;
1364 JPy_INCREF(pyObject);
1365
1366 JPy_END_GIL_STATE
1367
1368 return (jlong)pyObject;
1369 }
1370
1371 /**
1372 * Evaluate PyDict_Check against a Python object.
1373 *
1374 * @param jenv JNI environment.
1375 * @param jLibClass the PyLib class object
1376 * @param objId a pointer to a python object
1377 * @return true if objId is a python dictionary
1378 */
1379 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyDictCheck
1380 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1381 {
1382 jboolean result;
1383
1384 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1385
1386 if (PyDict_Check(((PyObject*) objId))) {
1387 result = JNI_TRUE;
1388 } else {
1389 result = JNI_FALSE;
1390 }
1391
1392 JPy_END_GIL_STATE
1393
1394 return result;
1395 }
1396
1397 /**
1398 * Evaluate PyList_Check against a Python object.
1399 *
1400 * @param jenv JNI environment.
1401 * @param jLibClass the PyLib class object
1402 * @param objId a pointer to a python object
1403 * @return true if objId is a python list
1404 */
1405 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyListCheck
1406 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1407 {
1408 jboolean result;
1409
1410 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1411
1412 if (PyList_Check(((PyObject*) objId))) {
1413 result = JNI_TRUE;
1414 } else {
1415 result = JNI_FALSE;
1416 }
1417
1418 JPy_END_GIL_STATE
1419
1420 return result;
1421 }
1422
1423 /**
1424 * Evaluate PyBool_Check against a Python object.
1425 *
1426 * @param jenv JNI environment.
1427 * @param jLibClass
1428 * @param objId a pointer to a python object
1429 * @return true if objId is a python boolean
1430 */
1431 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyBoolCheck
1432 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1433 {
1434 jboolean result;
1435
1436 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1437
1438 if (PyBool_Check(((PyObject*) objId))) {
1439 result = JNI_TRUE;
1440 } else {
1441 result = JNI_FALSE;
1442 }
1443
1444 JPy_END_GIL_STATE
1445
1446 return result;
1447 }
1448
1449 /**
1450 * Check equality against Py_None and a Python object.
1451 *
1452 * @param jenv JNI environment.
1453 * @param jLibClass
1454 * @param objId a pointer to a python object
1455 * @return true if objId is a None
1456 */
1457 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyNoneCheck
1458 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1459 {
1460 jboolean result;
1461
1462 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1463
1464 if (Py_None == (((PyObject*) objId))) {
1465 result = JNI_TRUE;
1466 } else {
1467 result = JNI_FALSE;
1468 }
1469
1470 JPy_END_GIL_STATE
1471
1472 return result;
1473 }
1474
1475 /**
1476 * Evaluate PyInt_Check against a Python object.
1477 *
1478 * @param jenv JNI environment.
1479 * @param jLibClass
1480 * @param objId a pointer to a python object
1481 * @return true if objId is a python int
1482 */
1483 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyIntCheck
1484 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1485 {
1486 int check;
1487
1488 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1489
1490 check = JPy_IS_CLONG(((PyObject*) objId));
1491
1492 JPy_END_GIL_STATE
1493
1494 return check ? (jboolean)JNI_TRUE : (jboolean)JNI_FALSE;
1495 }
1496
1497 /**
1498 * Evaluate PyLong_Check against a Python object.
1499 *
1500 * @param jenv JNI environment.
1501 * @param jLibClass
1502 * @param objId a pointer to a python object
1503 * @return true if objId is a python long
1504 */
1505 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyLongCheck
1506 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1507 {
1508 jboolean result;
1509
1510 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1511
1512 if (PyLong_Check(((PyObject*) objId))) {
1513 result = JNI_TRUE;
1514 } else {
1515 result = JNI_FALSE;
1516 }
1517
1518 JPy_END_GIL_STATE
1519
1520 return result;
1521 }
1522
1523 /**
1524 * Evaluate PyFloat_Check against a Python object.
1525 *
1526 * @param jenv JNI environment.
1527 * @param jLibClass
1528 * @param objId a pointer to a python object
1529 * @return true if objId is a python float
1530 */
1531 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyFloatCheck
1532 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1533 {
1534 jboolean result;
1535
1536 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1537
1538 if (PyFloat_Check(((PyObject*) objId))) {
1539 result = JNI_TRUE;
1540 } else {
1541 result = JNI_FALSE;
1542 }
1543
1544 JPy_END_GIL_STATE
1545
1546 return result;
1547 }
1548
1549 /**
1550 * Evaluate PyString_Check against a Python object.
1551 *
1552 * @param jenv JNI environment.
1553 * @param jLibClass
1554 * @param objId a pointer to a python object
1555 * @return true if objId is a python String
1556 */
1557 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyStringCheck
1558 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1559 {
1560 jboolean result;
1561
1562 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1563
1564 if (JPy_IS_STR(((PyObject*) objId))) {
1565 result = JNI_TRUE;
1566 } else {
1567 result = JNI_FALSE;
1568 }
1569
1570 JPy_END_GIL_STATE
1571
1572 return result;
1573 }
1574
1575 /**
1576 * Evaluate PyCallable_Check against a Python object.
1577 *
1578 * @param jenv JNI environment.
1579 * @param jLibClass
1580 * @param objId a pointer to a python object
1581 * @return true if objId is a python callable
1582 */
1583 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyCallableCheck
1584 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1585 {
1586 jboolean result;
1587
1588 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1589
1590 if (PyCallable_Check(((PyObject*) objId))) {
1591 result = JNI_TRUE;
1592 } else {
1593 result = JNI_FALSE;
1594 }
1595
1596 JPy_END_GIL_STATE
1597
1598 return result;
1599 }
1600
1601 /**
1602 * Evaluate PyFunction_Check against a Python object.
1603 *
1604 * @param jenv JNI environment.
1605 * @param jLibClass
1606 * @param objId a pointer to a python object
1607 * @return true if objId is a python function
1608 */
1609 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyFunctionCheck
1610 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1611 {
1612 jboolean result;
1613
1614 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1615
1616 if (PyFunction_Check(((PyObject*) objId))) {
1617 result = JNI_TRUE;
1618 } else {
1619 result = JNI_FALSE;
1620 }
1621
1622 JPy_END_GIL_STATE
1623
1624 return result;
1625 }
1626
1627 /**
1628 * Evaluate PyModule_Check against a Python object.
1629 *
1630 * @param jenv JNI environment.
1631 * @param jLibClass
1632 * @param objId a pointer to a python object
1633 * @return true if objId is a python module
1634 */
1635 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyModuleCheck
1636 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1637 {
1638 jboolean result;
1639
1640 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1641
1642 if (PyModule_Check(((PyObject*) objId))) {
1643 result = JNI_TRUE;
1644 } else {
1645 result = JNI_FALSE;
1646 }
1647
1648 JPy_END_GIL_STATE
1649
1650 return result;
1651 }
1652
1653 /**
1654 * Evaluate PyTuple_Check against a Python object.
1655 *
1656 * @param jenv JNI environment.
1657 * @param jLibClass
1658 * @param objId a pointer to a python object
1659 * @return true if objId is a python tuple
1660 */
1661 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyTupleCheck
1662 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1663 {
1664 jboolean result;
1665
1666 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1667
1668 if (PyTuple_Check(((PyObject*) objId))) {
1669 result = JNI_TRUE;
1670 } else {
1671 result = JNI_FALSE;
1672 }
1673
1674 JPy_END_GIL_STATE
1675
1676 return result;
1677 }
1678
1679 /**
1680 * Runs the str function on a Python object.
1681 *
1682 * @param jenv JNI environment.
1683 * @param jLibClass the class object for PyLib
1684 * @param objId a pointer to a python object
1685 * @return the Python toString of this object
1686 */
1687 JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_str
1688 (JNIEnv* jenv, jclass jLibClass, jlong objId) {
1689 PyObject *pyObject;
1690 jobject jObject;
1691 PyObject *pyStr;
1692
1693 JPy_BEGIN_GIL_STATE(NULL)
1694
1695 pyObject = (PyObject *) objId;
1696
1697 pyStr = PyObject_Str(pyObject);
1698 if (pyStr != NULL) {
1699 jObject = (*jenv)->NewStringUTF(jenv, JPy_AS_UTF8(pyStr));
1700 JPy_DECREF(pyStr);
1701 } else {
1702 jObject = NULL;
1703 PyLib_HandlePythonException(jenv);
1704 }
1705
1706 JPy_END_GIL_STATE
1707
1708 return jObject;
1709 }
1710
1711
1712 /**
1713 * Runs the repr function on a Python object.
1714 *
1715 * @param jenv JNI environment.
1716 * @param jLibClass the class object for PyLib
1717 * @param objId a pointer to a python object
1718 * @return the Python representation string of this object
1719 */
1720 JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_repr
1721 (JNIEnv* jenv, jclass jLibClass, jlong objId) {
1722 PyObject *pyObject;
1723 jobject jObject;
1724 PyObject *pyStr;
1725
1726 JPy_BEGIN_GIL_STATE(NULL)
1727
1728 pyObject = (PyObject *) objId;
1729
1730 pyStr = PyObject_Repr(pyObject);
1731 if (pyStr) {
1732 jObject = (*jenv)->NewStringUTF(jenv, JPy_AS_UTF8(pyStr));
1733 JPy_DECREF(pyStr);
1734 } else {
1735 jObject = NULL;
1736 }
1737
1738
1739 JPy_END_GIL_STATE
1740
1741 return jObject;
1742 }
1743
1744 /*
1745 * Compute and return the hash value of an object o. On failure, return -1.
1746 * This is the equivalent of the Python expression hash(o).
1747 *
1748 * @param jenv JNI environment.
1749 * @param jLibClass the class object for PyLib
1750 * @param objId a pointer to a python object
1751 * @return the hash code, -1 on failure
1752 */
1753 JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_hash
1754 (JNIEnv* jenv, jclass jLibClass, jlong objId)
1755 {
1756 PyObject* pyObject;
1757 long hash;
1758
1759 JPy_BEGIN_GIL_STATE(-1)
1760
1761 pyObject = (PyObject *) objId;
1762
1763 if ((hash = PyObject_Hash(pyObject)) == -1) {
1764 PyLib_HandlePythonException(jenv);
1765 }
1766
1767 JPy_END_GIL_STATE
1768
1769 return (jlong)hash;
1770 }
1771
1772 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_eq
1773 (JNIEnv* jenv, jclass jLibClass, jlong objId1, jobject other)
1774 {
1775 PyObject* pyObject1;
1776 PyObject* pyObject2;
1777 PyObject* eq;
1778 jboolean result = JNI_FALSE;
1779
1780 JPy_BEGIN_GIL_STATE(JNI_FALSE)
1781
1782 pyObject1 = (PyObject *) objId1;
1783 pyObject2 = PyLib_ConvertJavaToPythonObject(jenv, other);
1784
1785 // Note: there are subtle differences between PyObject_RichCompare and PyObject_RichCompareBool
1786 // that make PyObject_RichCompareBool unacceptable to use here.
1787 //
1788 // Specifically, PyObject_RichCompareBool says that it will return True for the same object
1789 // https://docs.python.org/2/c-api/object.html#c.PyObject_RichCompareBool
1790 // We *DON'T* want that, we want to delegate to the implementations __eq__ function instead.
1791 // i.e.
1792 /*
1793 >>> class AlwaysFalse:
1794 ... def __eq__(self, other):
1795 ... return False
1796 ...
1797 >>> a == a
1798 False
1799 */
1800
1801 eq = PyObject_RichCompare(pyObject1, pyObject2, Py_EQ);
1802 JPy_DECREF(pyObject2);
1803
1804 if (eq == NULL) {
1805 PyLib_HandlePythonException(jenv);
1806 } else if (PyBool_Check(eq)) {
1807 result = (eq == Py_True) ? JNI_TRUE : JNI_FALSE;
1808 JPy_DECREF(eq);
1809 } else {
1810 int val = PyObject_IsTrue(eq);
1811 JPy_DECREF(eq);
1812 if (val == -1) {
1813 PyLib_HandlePythonException(jenv);
1814 } else {
1815 result = val ? JNI_TRUE : JNI_FALSE;
1816 }
1817 }
1818
1819 JPy_END_GIL_STATE
1820
1821 return result;
1822 }
1823
1824 // TODO: this implementation *should* use JType_CreateJavaArray instead...
1825 /*
1826 * Class: org_jpy_PyLib
1827 * Method: getObjectArrayValue
1828 * Signature: (JLjava/lang/Class;)[Ljava/lang/Object;
1829 */
1830 JNIEXPORT jobjectArray JNICALL Java_org_jpy_PyLib_getObjectArrayValue
1831 (JNIEnv* jenv, jclass jLibClass, jlong objId, jclass itemClassRef)
1832 {
1833 PyObject* pyObject;
1834 jobject jObject;
1835
1836 JPy_BEGIN_GIL_STATE(NULL)
1837
1838 pyObject = (PyObject*) objId;
1839
1840 if (pyObject == Py_None) {
1841 jObject = NULL;
1842 } else if (JObj_Check(pyObject)) {
1843 jObject = ((JPy_JObj*) pyObject)->objectRef;
1844 } else if (PySequence_Check(pyObject)) {
1845 PyObject* pyItem;
1846 jobject jItem;
1847 jint i, length;
1848
1849 length = PySequence_Length(pyObject);
1850
1851 jObject = (*jenv)->NewObjectArray(jenv, length, itemClassRef, NULL);
1852
1853 for (i = 0; i < length; i++) {
1854 pyItem = PySequence_GetItem(pyObject, i);
1855 if (pyItem == NULL) {
1856 JPy_DELETE_LOCAL_REF(jObject);
1857 goto error;
1858 }
1859 if (JPy_AsJObject(jenv, pyItem, &jItem, JNI_FALSE) < 0) {
1860 JPy_DELETE_LOCAL_REF(jObject);
1861 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_getObjectArrayValue: error: failed to convert Python item to Java Object\n");
1862 PyLib_HandlePythonException(jenv);
1863 goto error;
1864 }
1865 JPy_XDECREF(pyItem);
1866 (*jenv)->SetObjectArrayElement(jenv, jObject, i, jItem);
1867 if ((*jenv)->ExceptionCheck(jenv)) {
1868 JPy_DELETE_LOCAL_REF(jObject);
1869 goto error;
1870 }
1871 }
1872 } else {
1873 jObject = NULL;
1874 (*jenv)->ThrowNew(jenv, JPy_RuntimeException_JClass, "python object cannot be converted to Object[]");
1875 }
1876
1877 error:
1878 JPy_END_GIL_STATE
1879
1880 return jObject;
1881 }
1882
1883
1884 /*
1885 * Class: org_jpy_python_PyLib
1886 * Method: getModule
1887 * Signature: (Ljava/lang/String;)J
1888 */
1889 JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_importModule
1890 (JNIEnv* jenv, jclass jLibClass, jstring jName)
1891 {
1892 PyObject* pyName;
1893 PyObject* pyModule = NULL;
1894 const char* nameChars;
1895
1896 JPy_BEGIN_GIL_STATE(0)
1897
1898 nameChars = (*jenv)->GetStringUTFChars(jenv, jName, NULL);
1899 if (nameChars == NULL) {
1900 PyLib_ThrowOOM(jenv);
1901 goto error;
1902 }
1903 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_importModule: name='%s'\n", nameChars);
1904 /* Note: pyName is a new reference */
1905 pyName = JPy_FROM_CSTR(nameChars);
1906 /* Note: pyModule is a new reference */
1907 pyModule = PyImport_Import(pyName);
1908 if (pyModule == NULL) {
1909 PyLib_HandlePythonException(jenv);
1910 }
1911 JPy_XDECREF(pyName);
1912
1913 error:
1914 if (nameChars != NULL) {
1915 (*jenv)->ReleaseStringUTFChars(jenv, jName, nameChars);
1916 }
1917
1918 JPy_END_GIL_STATE
1919
1920 return (jlong) pyModule;
1921 }
1922
1923
1924
1925
1926 /*
1927 * Class: org_jpy_python_PyLib
1928 * Method: getAttributeValue
1929 * Signature: (JLjava/lang/String;)J
1930 */
1931 JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_getAttributeObject
1932 (JNIEnv* jenv, jclass jLibClass, jlong objId, jstring jName)
1933 {
1934 PyObject* pyObject;
1935 PyObject* pyValue;
1936
1937 JPy_BEGIN_GIL_STATE(0)
1938
1939 pyObject = (PyObject*) objId;
1940 pyValue = PyLib_GetAttributeObject(jenv, pyObject, jName);
1941
1942 JPy_END_GIL_STATE
1943
1944 return (jlong) pyValue;
1945 }
1946
1947 /*
1948 * Class: org_jpy_python_PyLib
1949 * Method: getAttributeValue
1950 * Signature: (JLjava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;
1951 */
1952 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getAttributeValue
1953 (JNIEnv* jenv, jclass jLibClass, jlong objId, jstring jName, jclass jValueClass)
1954 {
1955 PyObject* pyObject;
1956 PyObject* pyValue;
1957 jobject jReturnValue;
1958
1959 JPy_BEGIN_GIL_STATE(NULL)
1960
1961 pyObject = (PyObject*) objId;
1962
1963 pyValue = PyLib_GetAttributeObject(jenv, pyObject, jName);
1964 if (pyValue == NULL) {
1965 jReturnValue = NULL;
1966 goto error;
1967 }
1968
1969 if (JPy_AsJObjectWithClass(jenv, pyValue, &jReturnValue, jValueClass) < 0) {
1970 jReturnValue = NULL;
1971 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_getAttributeValue: error: failed to convert attribute value\n");
1972 PyLib_HandlePythonException(jenv);
1973 }
1974
1975 error:
1976 JPy_XDECREF(pyValue);
1977 JPy_END_GIL_STATE
1978
1979 return jReturnValue;
1980 }
1981
1982
1983 /*
1984 * Class: org_jpy_python_PyLib
1985 * Method: setAttributeValue
1986 * Signature: (JLjava/lang/String;J)V
1987 */
1988 JNIEXPORT void JNICALL Java_org_jpy_PyLib_setAttributeValue
1989 (JNIEnv* jenv, jclass jLibClass, jlong objId, jstring jName, jobject jValue, jclass jValueClass)
1990 {
1991 PyObject* pyObject;
1992 const char* nameChars;
1993 PyObject* pyValue;
1994 JPy_JType* valueType;
1995
1996 JPy_BEGIN_GIL_STATE_VOID()
1997
1998 pyObject = (PyObject*) objId;
1999
2000 nameChars = (*jenv)->GetStringUTFChars(jenv, jName, NULL);
2001 if (nameChars == NULL) {
2002 PyLib_ThrowOOM(jenv);
2003 goto error;
2004 }
2005 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_setAttributeValue: objId=%p, name='%s', jValue=%p, jValueClass=%p\n", pyObject, nameChars, jValue, jValueClass);
2006
2007 if (jValueClass != NULL) {
2008 valueType = JType_GetType(jenv, jValueClass, JNI_FALSE);
2009 } else {
2010 valueType = NULL;
2011 }
2012
2013 if (valueType != NULL) {
2014 pyValue = JPy_FromJObjectWithType(jenv, jValue, valueType);
2015 } else {
2016 pyValue = JPy_FromJObject(jenv, jValue);
2017 }
2018
2019 if (pyValue == NULL) {
2020 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_setAttributeValue: error: attribute '%s': Java object not convertible\n", nameChars);
2021 PyLib_HandlePythonException(jenv);
2022 goto error;
2023 }
2024
2025 // PyObject_SetAttrString will increase ref count
2026 if (PyObject_SetAttrString(pyObject, nameChars, pyValue) < 0) {
2027 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_setAttributeValue: error: PyObject_SetAttrString failed on attribute '%s'\n", nameChars);
2028 PyLib_HandlePythonException(jenv);
2029 goto error;
2030 }
2031
2032 error:
2033 if (nameChars != NULL) {
2034 (*jenv)->ReleaseStringUTFChars(jenv, jName, nameChars);
2035 }
2036
2037 JPy_XDECREF(pyValue);
2038
2039 JPy_END_GIL_STATE
2040 }
2041
2042 /**
2043 * Deletes an attribute from an object.
2044 *
2045 * @param jenv JNI environment.
2046 * @param jLibClass the PyLib class object
2047 * @param objId a pointer to a python object
2048 * @param jName the java string naming the attribute to delete
2049 */
2050 JNIEXPORT void JNICALL Java_org_jpy_PyLib_delAttribute
2051 (JNIEnv* jenv, jclass jLibClass, jlong objId, jstring jName)
2052 {
2053 PyObject* pyObject;
2054 const char* nameChars;
2055
2056 JPy_BEGIN_GIL_STATE_VOID()
2057
2058 pyObject = (PyObject*) objId;
2059
2060 nameChars = (*jenv)->GetStringUTFChars(jenv, jName, NULL);
2061 if (nameChars == NULL) {
2062 PyLib_ThrowOOM(jenv);
2063 goto error;
2064 }
2065 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_delAttribute: objId=%p, name='%s'\n", pyObject, nameChars);
2066
2067 if (PyObject_DelAttrString(pyObject, nameChars) < 0) {
2068 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_delAttribute: error: PyObject_DelAttrString failed on attribute '%s'\n", nameChars);
2069 PyLib_HandlePythonException(jenv);
2070 goto error;
2071 }
2072
2073 error:
2074 if (nameChars != NULL) {
2075 (*jenv)->ReleaseStringUTFChars(jenv, jName, nameChars);
2076 }
2077
2078
2079 JPy_END_GIL_STATE
2080 }
2081
2082 /*
2083 * Checks for an attribute's existence.
2084 *
2085 * @param jenv JNI environment.
2086 * @param jLibClass the PyLib class object
2087 * @param objId a pointer to a python object
2088 * @param jName the java string naming the attribute to delete
2089 *
2090 * @return true if the attribute exists on this object
2091 */
2092
2093 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_hasAttribute
2094 (JNIEnv* jenv, jclass jLibClass, jlong objId, jstring jName)
2095 {
2096 PyObject* pyObject;
2097 const char* nameChars;
2098 jboolean result = JNI_FALSE;
2099
2100 JPy_BEGIN_GIL_STATE(JNI_FALSE)
2101
2102 pyObject = (PyObject*) objId;
2103
2104 nameChars = (*jenv)->GetStringUTFChars(jenv, jName, NULL);
2105 if (nameChars == NULL) {
2106 PyLib_ThrowOOM(jenv);
2107 goto error;
2108 }
2109 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "Java_org_jpy_PyLib_delAttribute: objId=%p, name='%s'\n", pyObject, nameChars);
2110
2111 result = PyObject_HasAttrString(pyObject, nameChars) ? JNI_TRUE : JNI_FALSE;
2112
2113 error:
2114 if (nameChars != NULL) {
2115 (*jenv)->ReleaseStringUTFChars(jenv, jName, nameChars);
2116 }
2117
2118 JPy_END_GIL_STATE
2119
2120 return result;
2121 }
2122
2123 /*
2124 * Class: org_jpy_PyLib
2125 * Method: hasGil
2126 * Signature: ()Z
2127 */
2128 JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_hasGil
2129 (JNIEnv* jenv, jclass jLibClass)
2130 {
2131 jboolean result;
2132
2133 // Note: we *don't* need the GIL to inquire if we have the GIL, that would be silly.
2134 result = PyGILState_Check() ? JNI_TRUE : JNI_FALSE;
2135 return result;
2136 }
2137
2138 /*
2139 * Class: org_jpy_PyLib
2140 * Method: ensureGil
2141 * Signature: (Ljava/util/function/Supplier;)Ljava/lang/Object;
2142 */
2143 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_ensureGil
2144 (JNIEnv* jenv, jclass jLibClass, jobject supplier)
2145 {
2146 jobject result;
2147 JPy_BEGIN_GIL_STATE(NULL)
2148 result = (*jenv)->CallObjectMethod(jenv, supplier, JPy_Supplier_get_MID);
2149 JPy_END_GIL_STATE
2150 return result;
2151 }
2152
2153
2154 /*
2155 * Class: org_jpy_python_PyLib
2156 * Method: call
2157 * Signature: (JZLjava/lang/String;I[Ljava/lang/Object;[Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/Object;
2158 */
2159 JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_callAndReturnObject
2160 (JNIEnv *jenv, jclass jLibClass, jlong objId, jboolean isMethodCall, jstring jName, jint argCount, jobjectArray jArgs, jobjectArray jParamClasses)
2161 {
2162 PyObject* pyObject;
2163 PyObject* pyReturnValue;
2164
2165 JPy_BEGIN_GIL_STATE(0)
2166
2167 pyObject = (PyObject*) objId;
2168 pyReturnValue = PyLib_CallAndReturnObject(jenv, pyObject, isMethodCall, jName, argCount, jArgs, jParamClasses);
2169
2170 JPy_END_GIL_STATE
2171
2172 return (jlong) pyReturnValue;
2173 }
2174
2175
2176 /*
2177 * Class: org_jpy_python_PyLib
2178 * Method: callAndReturnValue
2179 * Signature: (JZLjava/lang/String;I[Ljava/lang/Object;[Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/Object;
2180 */
2181 JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_callAndReturnValue
2182 (JNIEnv *jenv, jclass jLibClass, jlong objId, jboolean isMethodCall, jstring jName, jint argCount, jobjectArray jArgs, jobjectArray jParamClasses, jclass jReturnClass)
2183 {
2184 PyObject* pyObject = (PyObject*) objId;
2185 PyObject* pyReturnValue;
2186 jobject jReturnValue = NULL;
2187
2188 JPy_BEGIN_GIL_STATE(NULL)
2189
2190 pyReturnValue = PyLib_CallAndReturnObject(jenv, pyObject, isMethodCall, jName, argCount, jArgs, jParamClasses);
2191 if (pyReturnValue == NULL) {
2192 goto error;
2193 }
2194
2195 if (JPy_AsJObjectWithClass(jenv, pyReturnValue, &jReturnValue, jReturnClass) < 0) {
2196 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "Java_org_jpy_PyLib_callAndReturnValue: error: failed to convert attribute value\n");
2197 PyLib_HandlePythonException(jenv);
2198 jReturnValue = NULL;
2199 goto error;
2200 }
2201
2202 error:
2203 JPy_XDECREF(pyReturnValue);
2204 JPy_END_GIL_STATE
2205
2206 return jReturnValue;
2207 }
2208
2209
2210 /*
2211 * Class: org_jpy_python_PyLib
2212 * Method: getDiagFlags
2213 * Signature: ()I
2214 */
2215 JNIEXPORT jint JNICALL Java_org_jpy_PyLib_00024Diag_getFlags
2216 (JNIEnv *jenv, jclass classRef)
2217 {
2218 return JPy_DiagFlags;
2219 }
2220
2221 /*
2222 * Class: org_jpy_python_PyLib
2223 * Method: setDiagFlags
2224 * Signature: (I)V
2225 */
2226 JNIEXPORT void JNICALL Java_org_jpy_PyLib_00024Diag_setFlags
2227 (JNIEnv *jenv, jclass classRef, jint flags)
2228 {
2229 JPy_DiagFlags = flags;
2230 }
2231
2232 ////////////////////////////////////////////////////////////////////////////////////
2233 // Helpers that also throw Java exceptions
2234
2235
2236 PyObject* PyLib_GetAttributeObject(JNIEnv* jenv, PyObject* pyObject, jstring jName)
2237 {
2238 PyObject* pyValue = NULL;
2239 const char* nameChars;
2240
2241 nameChars = (*jenv)->GetStringUTFChars(jenv, jName, NULL);
2242 if (nameChars == NULL) {
2243 PyLib_ThrowOOM(jenv);
2244 goto error;
2245 }
2246 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "PyLib_GetAttributeObject: objId=%p, name='%s'\n", pyObject, nameChars);
2247 /* Note: pyValue is a new reference */
2248 pyValue = PyObject_GetAttrString(pyObject, nameChars);
2249 if (pyValue == NULL) {
2250 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_GetAttributeObject: error: attribute not found '%s'\n", nameChars);
2251 PyLib_HandlePythonException(jenv);
2252 }
2253 error:
2254 if (nameChars != NULL) {
2255 (*jenv)->ReleaseStringUTFChars(jenv, jName, nameChars);
2256 }
2257 return pyValue;
2258 }
2259
•2260 PyObject* PyLib_FromJObjectForTuple(JNIEnv *jenv, jobject jArg, jclass jParamClass, const char* nameChars, jint index) {
2261 JPy_JType* implicitParamType;
2262 JPy_JType* explicitParamType;
2263 PyObject* pyReturnValue;
2264
2265 // if jArg is NULL, we don't care about the implicit / explicit types, we'll return None
2266 if (jArg == NULL) {
2267 return JPy_FROM_JNULL();
2268 }
2269
2270 pyReturnValue = NULL;
2271 explicitParamType = NULL;
2272 implicitParamType = JType_GetTypeForObject(jenv, jArg, JNI_FALSE);
2273 if (implicitParamType == NULL) {
2274 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_FromJObjectForTuple: error: callable '%s': argument %d: failed to retrieve implicit-type\n", nameChars, index);
2275 PyLib_HandlePythonException(jenv);
2276 goto error;
2277 }
2278
2279 if (jParamClass != NULL) {
2280 explicitParamType = JType_GetType(jenv, jParamClass, JNI_FALSE);
2281 if (explicitParamType == NULL) {
2282 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_FromJObjectForTuple: error: callable '%s': argument %d: failed to retrieve explicit-type\n", nameChars, index);
2283 PyLib_HandlePythonException(jenv);
2284 goto error;
2285 }
2286 pyReturnValue = JPy_FromJObjectWithType(jenv, jArg, explicitParamType);
2287 } else {
2288 pyReturnValue = JPy_FromJObjectWithType(jenv, jArg, implicitParamType);
2289 }
2290
2291 error:
2292 JPy_XDECREF(explicitParamType);
2293 JPy_XDECREF(implicitParamType);
2294 return pyReturnValue;
2295 }
2296
2297
2298 PyObject* PyLib_CallAndReturnObject(JNIEnv *jenv, PyObject* pyObject, jboolean isMethodCall, jstring jName, jint argCount, jobjectArray jArgs, jobjectArray jParamClasses)
2299 {
2300 PyObject* pyCallable = NULL;
2301 PyObject* pyArgs = NULL;
2302 PyObject* pyArg;
2303 PyObject* pyReturnValue = NULL;
2304 const char* nameChars;
2305 jint i;
2306 jobject jArg;
2307 jclass jParamClass = NULL;
2308 JPy_JType* explicitParamType = NULL;
2309 JPy_JType* jArgParamType;
2310
2311 nameChars = (*jenv)->GetStringUTFChars(jenv, jName, NULL);
2312 if (nameChars == NULL) {
2313 PyLib_ThrowOOM(jenv);
2314 goto error;
2315 }
2316
2317 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "PyLib_CallAndReturnObject: objId=%p, isMethodCall=%d, name='%s', argCount=%d\n", pyObject, isMethodCall, nameChars, argCount);
2318
2319 // Note: pyCallable is a new reference
2320 pyCallable = PyObject_GetAttrString(pyObject, nameChars);
2321 if (pyCallable == NULL) {
2322 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_CallAndReturnObject: error: function or method not found: '%s'\n", nameChars);
2323 PyLib_HandlePythonException(jenv);
2324 goto error;
2325 }
2326
2327 if (!PyCallable_Check(pyCallable)) {
2328 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_CallAndReturnObject: error: object is not callable: '%s'\n", nameChars);
2329 PyLib_HandlePythonException(jenv);
2330 goto error;
2331 }
2332
2333 pyArgs = PyTuple_New(argCount);
2334 for (i = 0; i < argCount; i++) {
2335 // get the implicit java type (the real type of the object)
2336 jArg = (*jenv)->GetObjectArrayElement(jenv, jArgs, i);
2337 if (jParamClasses != NULL) {
2338 jParamClass = (*jenv)->GetObjectArrayElement(jenv, jParamClasses, i);
2339 }
2340 pyArg = PyLib_FromJObjectForTuple(jenv, jArg, jParamClass, nameChars, i);
2341 if (jParamClass != NULL) {
2342 JPy_DELETE_LOCAL_REF(jParamClass);
2343 }
2344 JPy_DELETE_LOCAL_REF(jArg);
2345 if (pyArg == NULL) {
2346 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_CallAndReturnObject: error: callable '%s': argument %d: failed to convert Java into Python object\n", nameChars, i);
2347 PyLib_HandlePythonException(jenv);
2348 goto error;
2349 }
2350 // pyArg reference stolen here
2351 PyTuple_SetItem(pyArgs, i, pyArg);
2352 }
2353
2354 // Check why: for some reason, we don't need the following code to invoke object methods.
2355 /*
2356 if (isMethodCall) {
2357 PyObject* pyMethod;
2358
2359 pyMethod = PyMethod_New(pyCallable, pyObject);
2360 if (pyMethod == NULL) {
2361 JPy_DIAG_PRINT(JPy_DIAG_F_EXEC, "PyLib_CallAndReturnObject: error: callable '%s': no memory\n", nameChars);
2362 PyLib_HandlePythonException(jenv);
2363 goto error;
2364 }
2365 JPy_DECREF(pyCallable);
2366 pyCallable = pyMethod;
2367 }
2368 */
2369
2370 pyReturnValue = PyObject_CallObject(pyCallable, argCount > 0 ? pyArgs : NULL);
2371 if (pyReturnValue == NULL) {
2372 JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_CallAndReturnObject: error: callable '%s': call returned NULL\n", nameChars);
2373 PyLib_HandlePythonException(jenv);
2374 goto error;
2375 }
2376
2377 error:
2378 if (nameChars != NULL) {
2379 (*jenv)->ReleaseStringUTFChars(jenv, jName, nameChars);
2380 }
2381 JPy_XDECREF(pyCallable);
2382 JPy_XDECREF(pyArgs);
2383
2384 return pyReturnValue;
2385 }
2386
2387 #define JPY_ERR_BASE_MSG "Error in Python interpreter"
2388 #define JPY_NO_INFO_MSG JPY_ERR_BASE_MSG ", no information available"
2389
2390 /**
2391 * Translates the current Python exception — including its full __cause__ / __context__
2392 * chain — into a Java exception and throws it.
2393 *
2394 * Formatting is delegated entirely to Python's own traceback.format_exception(), which
2395 * faithfully reproduces the output that the Python interpreter would print itself:
2396 * chained exceptions, ExceptionGroups (3.11+), and any future exception-display changes
2397 * are all handled automatically without any C-side formatting logic.
2398 *
2399 * On Python >= 3.12 the deprecated PyErr_Fetch / PyErr_NormalizeException trio is
2400 * replaced with PyErr_GetRaisedException(), which returns a single already-normalized
2401 * exception object with its __traceback__ already attached.
2402 *
2403 * Note on stack-frame limits and recursive-line cutoffs
2404 * ------------------------------------------------------
2405 * The previous hand-rolled C formatter imposed a hard frame limit (1024) and a
2406 * recursive-line cutoff (3) because it managed a growable C string buffer manually
2407 * and needed to bound memory growth. Neither constant is carried forward here:
2408 *
2409 * - traceback.format_exception() manages all string memory through the Python
2410 * allocator, so there is no C buffer to protect.
2411 * - Python's interpreter already enforces sys.getrecursionlimit() (default 1000),
2412 * which practically caps traceback depth without any extra limit on our side.
2413 * - The traceback module natively compresses repeated frames into
2414 * "[Previous line repeated N more times]", making deep recursive tracebacks
2415 * compact without truncating useful information.
2416 * - Imposing our own limit would silently drop the outermost frames, which are
2417 * often the most useful ones for diagnosing the root cause.
2418 */
2419 void PyLib_HandlePythonException(JNIEnv* jenv)
2420 {
2421 if (PyErr_Occurred() == NULL) {
2422 return;
2423 }
2424
2425 /* pyValue is an alias used only for Java exception-class selection below. */
2426 PyObject* pyValue = NULL;
2427 jclass jExceptionClass;
2428 int threw = 0;
2429
2430 #if PY_VERSION_HEX >= 0x030C0000 /* >= 3.12 */
2431 /* Returns a single normalized exception object with __traceback__ already attached,
2432 * and clears the error indicator. Replaces the deprecated PyErr_Fetch /
2433 * PyErr_NormalizeException / PyErr_Restore trio. */
2434 PyObject* pyExc = PyErr_GetRaisedException();
2435 pyValue = pyExc;
2436 #else
2437 PyObject* pyType = NULL;
2438 PyObject* pyTraceback = NULL;
2439 PyErr_Fetch(&pyType, &pyValue, &pyTraceback);
2440 PyErr_NormalizeException(&pyType, &pyValue, &pyTraceback);
2441 #endif
2442
2443 /* Select the Java exception class to throw. */
2444 if (pyValue != NULL && PyObject_TypeCheck(pyValue, (PyTypeObject*) PyExc_KeyError)) {
2445 jExceptionClass = JPy_KeyError_JClass;
2446 } else if (pyValue != NULL && PyObject_TypeCheck(pyValue, (PyTypeObject*) PyExc_StopIteration)) {
2447 jExceptionClass = JPy_StopIteration_JClass;
2448 } else {
2449 jExceptionClass = JPy_RuntimeException_JClass;
2450 }
2451
2452 /* Delegate to Python's own traceback module to format the full exception chain.
2453 * This handles __cause__, __context__, __suppress_context__, ExceptionGroups, etc.
2454 * — everything the previous hand-rolled C formatter silently discarded. */
2455 PyObject* tbModule = PyImport_ImportModule("traceback");
2456 if (tbModule != NULL) {
2457 PyObject* formatted = NULL;
2458 #if PY_VERSION_HEX >= 0x030C0000 /* single-argument form available since 3.10, safe here */
2459 formatted = PyObject_CallMethod(tbModule, "format_exception", "O", pyExc);
2460 #else
2461 /* Three-argument form works on all supported Python versions. */
2462 formatted = PyObject_CallMethod(tbModule, "format_exception", "OOO",
2463 pyType, pyValue,
2464 pyTraceback != NULL ? pyTraceback : Py_None);
2465 #endif
2466 JPy_DECREF(tbModule);
2467
2468 if (formatted != NULL) {
2469 /* format_exception returns a list of strings; join, prefix, and encode them.
2470 * Each step is conditional on the previous succeeding; all temporaries are
2471 * released together in the flat cleanup block below. */
2472 PyObject* sep = PyUnicode_FromString("");
2473 PyObject* joined = sep != NULL ? PyUnicode_Join(sep, formatted) : NULL;
2474 PyObject* prefixed = joined != NULL ? PyUnicode_FromFormat(JPY_ERR_BASE_MSG ":\n%U", joined) : NULL;
2475 PyObject* joinedUtf8 = prefixed != NULL ? PyUnicode_AsEncodedString(prefixed, "utf-8", "replace") : NULL;
2476
2477 if (joinedUtf8 != NULL) {
2478 (*jenv)->ThrowNew(jenv, jExceptionClass, PyBytes_AsString(joinedUtf8));
2479 threw = 1;
2480 }
2481
2482 JPy_XDECREF(joinedUtf8);
2483 JPy_XDECREF(prefixed);
2484 JPy_XDECREF(joined);
2485 JPy_XDECREF(sep);
2486 JPy_DECREF(formatted);
2487 }
2488 }
2489
2490 if (!threw) {
2491 /* Fallback: traceback module unavailable or an intermediate step failed. */
2492 (*jenv)->ThrowNew(jenv, jExceptionClass, JPY_NO_INFO_MSG);
2493 }
2494
2495 #if PY_VERSION_HEX >= 0x030C0000
2496 JPy_XDECREF(pyExc);
2497 #else
2498 JPy_XDECREF(pyType);
2499 JPy_XDECREF(pyValue);
2500 JPy_XDECREF(pyTraceback);
2501 #endif
2502 PyErr_Clear();
2503 }
2504
2505 /**
2506 * Throw an OutOfMemoryError.
2507 * @param jenv the jni environment
2508 */
2509 void PyLib_ThrowOOM(JNIEnv* jenv) {
2510 (*jenv)->ThrowNew(jenv, JPy_OutOfMemoryError_JClass, "Out of memory");
2511 }
2512
2513 /**
2514 * Throw a FileNotFoundException.
2515 * @param jenv the jni environment
2516 */
2517 void PyLib_ThrowFNFE(JNIEnv* jenv, const char *file) {
2518 (*jenv)->ThrowNew(jenv, JPy_FileNotFoundException_JClass, file);
2519 }
2520
2521 /**
2522 * Throw an UnsupportedOperationException.
2523 * @param jenv the jni environment
2524 * @param message the exception message
2525 */
2526 void PyLib_ThrowUOE(JNIEnv* jenv, const char *message) {
2527 (*jenv)->ThrowNew(jenv, JPy_UnsupportedOperationException_JClass, message);
2528 }
2529
2530 /**
2531 * Throw an UnsupportedOperationException.
2532 * @param jenv the jni environment
2533 * @param message the exception message
2534 */
2535 void PyLib_ThrowRTE(JNIEnv* jenv, const char *message) {
2536 (*jenv)->ThrowNew(jenv, JPy_RuntimeException_JClass, message);
2537 }
2538
2539 ////////////////////////////////////////////////////////////////////////////////////////////////
2540 // Redirect stdout
2541
2542 static PyObject* JPrint_write(PyObject* self, PyObject* args)
2543 {
2544 if (stdout != NULL) {
2545 const char* text;
2546 if (!PyArg_ParseTuple(args, "s", &text)) {
2547 return NULL;
2548 }
2549 fprintf(stdout, "%s", text);
2550 }
2551 Py_RETURN_NONE;
2552 }
2553
2554 static PyObject* JPrint_flush(PyObject* self, PyObject* args)
2555 {
2556 if (stdout != NULL) {
2557 fflush(stdout);
2558 }
2559 Py_RETURN_NONE;
2560 }
2561
2562 static PyMethodDef JPrint_Functions[] = {
2563
2564 {"write", (PyCFunction) JPrint_write, METH_VARARGS,
2565 "Internal function. Used to print to stdout in embedded mode."},
2566
2567 {"flush", (PyCFunction) JPrint_flush, METH_VARARGS,
2568 "Internal function. Used to flush to stdout in embedded mode."},
2569
2570 {NULL, NULL, 0, NULL} /*Sentinel*/
2571 };
2572
2573 #define JPY_STDOUT_MODULE_NAME "jpy_stdout"
2574 #define JPY_STDOUT_MODULE_DOC "Redirect 'stdout' to the console in embedded mode"
2575
2576 static struct PyModuleDef JPrint_ModuleDef =
2577 {
2578 PyModuleDef_HEAD_INIT,
2579 JPY_STDOUT_MODULE_NAME, /* Name of the Python JPy_Module */
2580 JPY_STDOUT_MODULE_DOC, /* Module documentation */
2581 -1, /* Size of per-interpreter state of the JPy_Module, or -1 if the JPy_Module keeps state in global variables. */
2582 JPrint_Functions, /* Structure containing global jpy-functions */
2583 NULL, // m_reload
2584 NULL, // m_traverse
2585 NULL, // m_clear
2586 NULL // m_free
2587 };
2588
2589 void PyLib_RedirectStdOut(void)
2590 {
2591 PyObject* module;
2592 module = PyModule_Create(&JPrint_ModuleDef);
2593 PySys_SetObject("stdout", module);
2594 PySys_SetObject("stderr", module);
2595 }
2596