Debian Codegraph @

src/main/c/jni/org_jpy_PyLib.c

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