-
Notifications
You must be signed in to change notification settings - Fork 144
/
pyembed.c
1907 lines (1545 loc) · 51.9 KB
/
pyembed.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 c-style: "K&R" -*- */
/*
jep - Java Embedded Python
Copyright (c) 2016 JEP AUTHORS.
This file is licensed under the the zlib/libpng License.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*****************************************************************************
This file handles two main things:
- startup, shutdown of interpreters.
(those are the pyembed_* functions)
- setting of parameters
(the pyembed_set*)
The really interesting stuff is not here. :-) This file simply makes calls
to the type definitions for pyjobject, etc.
*****************************************************************************
*/
#if STDC_HEADERS
#include <stdio.h>
#endif
#include "Jep.h"
/*
* fixes compiler warnings about PyMarshal_ReadLongFromFile and
* PyMarshal_ReadLastObjectFromFile
*/
#include "marshal.h"
#ifdef __APPLE__
#ifndef WITH_NEXT_FRAMEWORK
#include <crt_externs.h>
// workaround for
// http://bugs.python.org/issue1602133
char **environ = NULL;
#endif
#endif
static PyThreadState *mainThreadState = NULL;
int pyembed_version_unsafe(void);
static PyObject* pyembed_findclass(PyObject*, PyObject*);
static PyObject* pyembed_forname(PyObject*, PyObject*);
static PyObject* pyembed_set_print_stack(PyObject*, PyObject*);
static PyObject* pyembed_jproxy(PyObject*, PyObject*);
static int maybe_pyc_file(FILE*, const char*, const char*, int);
static void pyembed_run_pyc(JepThread *jepThread, FILE *);
// ClassLoader.loadClass
static jmethodID loadClassMethod = 0;
// jep.Proxy.newProxyInstance
static jmethodID newProxyMethod = 0;
#if PY_MAJOR_VERSION < 3
// Integer(int)
static jmethodID integerIConstructor = 0;
#endif
// Long(long)
static jmethodID longJConstructor = 0;
// Double(double)
static jmethodID doubleDConstructor = 0;
// Boolean(boolean)
static jmethodID booleanBConstructor = 0;
// ArrayList(int)
static jmethodID arraylistIConstructor = 0;
static jmethodID arraylistAdd = 0;
// HashMap(int)
static jmethodID hashmapIConstructor = 0;
static jmethodID hashmapPut = 0;
static struct PyMethodDef jep_methods[] = {
{
"findClass",
pyembed_findclass,
METH_VARARGS,
"Find and instantiate a system class, somewhat faster than forName."
},
{
"forName",
pyembed_forname,
METH_VARARGS,
"Find and return a jclass object using the supplied ClassLoader."
},
{
"jarray",
pyjarray_new_v,
METH_VARARGS,
"Create a new primitive array in Java.\n"
"Accepts:\n"
"(size, type _ID, [0]) || "
"(size, JCHAR_ID, [string value] || "
"(size, jobject) || "
"(size, str) || "
"(size, jarray)"
},
{
"printStack",
pyembed_set_print_stack,
METH_VARARGS,
"Turn on printing of stack traces (True|False)"
},
{
"jproxy",
pyembed_jproxy,
METH_VARARGS,
"Create a Proxy class for a Python object.\n"
"Accepts two arguments: ([a class object], [list of java interfaces "
"to implement, string names])"
},
{ NULL, NULL }
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef jep_module_def = {
PyModuleDef_HEAD_INIT,
"_jep", /* m_name */
"_jep", /* m_doc */
-1, /* m_size */
jep_methods, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
static PyObject* initjep(void)
{
PyObject *modjep;
#if PY_MAJOR_VERSION >= 3
PyObject *sysmodules;
modjep = PyModule_Create(&jep_module_def);
sysmodules = PyImport_GetModuleDict();
PyDict_SetItemString(sysmodules, "_jep", modjep);
#else
PyImport_AddModule("_jep");
Py_InitModule((char *) "_jep", jep_methods);
#endif
modjep = PyImport_ImportModule("_jep");
if (modjep == NULL) {
printf("WARNING: couldn't import module _jep.\n");
} else {
// stuff for making new pyjarray objects
PyModule_AddIntConstant(modjep, "JBOOLEAN_ID", JBOOLEAN_ID);
PyModule_AddIntConstant(modjep, "JINT_ID", JINT_ID);
PyModule_AddIntConstant(modjep, "JLONG_ID", JLONG_ID);
PyModule_AddIntConstant(modjep, "JSTRING_ID", JSTRING_ID);
PyModule_AddIntConstant(modjep, "JDOUBLE_ID", JDOUBLE_ID);
PyModule_AddIntConstant(modjep, "JSHORT_ID", JSHORT_ID);
PyModule_AddIntConstant(modjep, "JFLOAT_ID", JFLOAT_ID);
PyModule_AddIntConstant(modjep, "JCHAR_ID", JCHAR_ID);
PyModule_AddIntConstant(modjep, "JBYTE_ID", JBYTE_ID);
PyModule_AddIntConstant(modjep, "JEP_NUMPY_ENABLED", JEP_NUMPY_ENABLED);
}
return modjep;
}
void pyembed_startup(void)
{
#ifdef __APPLE__
#ifndef WITH_NEXT_FRAMEWORK
// workaround for
// http://bugs.python.org/issue1602133
environ = *_NSGetEnviron();
#endif
#endif
if (mainThreadState != NULL) {
// this shouldn't happen but to be safe, don't initialize twice
return;
}
if (pyembed_version_unsafe()) {
return;
}
Py_Initialize();
PyEval_InitThreads();
// save a pointer to the main PyThreadState object
mainThreadState = PyThreadState_Get();
PyEval_ReleaseThread(mainThreadState);
}
/*
* Verify the Python major.minor at runtime matches the Python major.minor
* that Jep was built against. If they don't match, refuse to initialize Jep
* and instead throw an exception because a mismatch could cause a JVM crash.
*/
int pyembed_version_unsafe(void)
{
const char *pyversion = NULL;
char *version = NULL;
char *major = NULL;
char *minor = NULL;
int i = 0;
pyversion = Py_GetVersion();
version = malloc(sizeof(char) * strlen(pyversion));
strcpy(version, pyversion);
major = version;
while (version[i] != '\0') {
if (!isdigit(version[i])) {
version[i] = '\0';
if (minor == NULL) {
minor = version + i + 1;
}
}
i += 1;
}
if (atoi(major) != PY_MAJOR_VERSION || atoi(minor) != PY_MINOR_VERSION) {
char *msg;
JNIEnv *env = pyembed_get_env();
msg = malloc(sizeof(char) * 200);
memset(msg, '\0', 200);
sprintf(msg,
"Jep will not initialize because it was compiled against Python %i.%i but is running against Python %s.%s",
PY_MAJOR_VERSION, PY_MINOR_VERSION, major, minor);
THROW_JEP(env, msg);
free(version);
free(msg);
return 1;
}
free(version);
return 0;
}
void pyembed_shutdown(JavaVM *vm)
{
JNIEnv *env;
// shut down python first
PyEval_AcquireThread(mainThreadState);
Py_Finalize();
if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
// failed to get a JNIEnv*, we can hope it's just shutting down fast
return;
} else {
// delete global references
unref_cache_primitive_classes(env);
unref_cache_frequent_classes(env);
}
}
intptr_t pyembed_thread_init(JNIEnv *env, jobject cl, jobject caller)
{
JepThread *jepThread;
PyObject *tdict, *mod_main, *globals;
if (cl == NULL) {
THROW_JEP(env, "Invalid Classloader.");
return 0;
}
PyEval_AcquireThread(mainThreadState);
jepThread = PyMem_Malloc(sizeof(JepThread));
if (!jepThread) {
THROW_JEP(env, "Out of memory.");
PyEval_ReleaseThread(mainThreadState);
return 0;
}
jepThread->tstate = Py_NewInterpreter();
/*
* Py_NewInterpreter() seems to take the thread state, but we're going to
* save/release and reacquire it since that doesn't seem documented
*/
PyEval_SaveThread();
PyEval_AcquireThread(jepThread->tstate);
// store java.lang.Class objects for later use.
// it's a noop if already done, but to synchronize, have the lock first
if (!cache_frequent_classes(env)) {
printf("WARNING: Failed to get and cache frequent class types!\n");
}
if (!cache_primitive_classes(env)) {
printf("WARNING: Failed to get and cache primitive class types!\n");
}
mod_main = PyImport_AddModule("__main__"); /* borrowed */
if (mod_main == NULL) {
THROW_JEP(env, "Couldn't add module __main__.");
PyEval_ReleaseThread(jepThread->tstate);
return 0;
}
globals = PyModule_GetDict(mod_main);
Py_INCREF(globals);
// init static module
jepThread->modjep = initjep();
jepThread->globals = globals;
jepThread->env = env;
jepThread->classloader = (*env)->NewGlobalRef(env, cl);
jepThread->caller = (*env)->NewGlobalRef(env, caller);
jepThread->printStack = 0;
jepThread->fqnToPyJmethods = NULL;
if ((tdict = PyThreadState_GetDict()) != NULL) {
PyObject *key, *t;
#if PY_MAJOR_VERSION >= 3
t = PyCapsule_New((void *) jepThread, NULL, NULL);
#else
t = (PyObject *) PyCObject_FromVoidPtr((void *) jepThread, NULL);
#endif
key = PyString_FromString(DICT_KEY);
PyDict_SetItem(tdict, key, t); /* takes ownership */
Py_DECREF(key);
Py_DECREF(t);
}
PyEval_ReleaseThread(jepThread->tstate);
return (intptr_t) jepThread;
}
void pyembed_thread_close(JNIEnv *env, intptr_t _jepThread)
{
JepThread *jepThread;
PyObject *tdict, *key;
jepThread = (JepThread *) _jepThread;
if (!jepThread) {
printf("WARNING: thread_close, invalid JepThread pointer.\n");
return;
}
PyEval_AcquireThread(jepThread->tstate);
key = PyString_FromString(DICT_KEY);
if ((tdict = PyThreadState_GetDict()) != NULL && key != NULL) {
PyDict_DelItem(tdict, key);
}
Py_DECREF(key);
Py_CLEAR(jepThread->globals);
Py_CLEAR(jepThread->fqnToPyJmethods);
Py_CLEAR(jepThread->modjep);
if (jepThread->classloader) {
(*env)->DeleteGlobalRef(env, jepThread->classloader);
}
if (jepThread->caller) {
(*env)->DeleteGlobalRef(env, jepThread->caller);
}
Py_EndInterpreter(jepThread->tstate);
PyMem_Free(jepThread);
PyEval_ReleaseLock();
}
JNIEnv* pyembed_get_env(void)
{
JavaVM *jvm;
JNIEnv *env;
JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
(*jvm)->AttachCurrentThread(jvm, (void**) &env, NULL);
return env;
}
// get thread struct when called from internals.
// NULL if not found.
// hold the lock before calling.
JepThread* pyembed_get_jepthread(void)
{
PyObject *tdict, *t, *key;
JepThread *ret = NULL;
key = PyString_FromString(DICT_KEY);
if ((tdict = PyThreadState_GetDict()) != NULL && key != NULL) {
t = PyDict_GetItem(tdict, key); /* borrowed */
if (t != NULL && !PyErr_Occurred()) {
#if PY_MAJOR_VERSION >= 3
ret = (JepThread*) PyCapsule_GetPointer(t, NULL);
#else
ret = (JepThread*) PyCObject_AsVoidPtr(t);
#endif
}
}
Py_DECREF(key);
return ret;
}
// used by _forname
#define LOAD_CLASS_METHOD(env, cl) \
{ \
if(loadClassMethod == 0) { \
jobject clazz; \
\
clazz = (*env)->GetObjectClass(env, cl); \
if(process_java_exception(env) || !clazz) \
return NULL; \
\
loadClassMethod = \
(*env)->GetMethodID(env, \
clazz, \
"loadClass", \
"(Ljava/lang/String;)Ljava/lang/Class;"); \
\
if(process_java_exception(env) || !loadClassMethod) { \
(*env)->DeleteLocalRef(env, clazz); \
return NULL; \
} \
\
(*env)->DeleteLocalRef(env, clazz); \
} \
}
static PyObject* pyembed_jproxy(PyObject *self, PyObject *args)
{
PyThreadState *_save;
JepThread *jepThread;
JNIEnv *env = NULL;
PyObject *pytarget;
PyObject *interfaces;
jclass clazz;
jobject cl;
jobject classes;
Py_ssize_t inum, i;
jobject proxy;
if (!PyArg_ParseTuple(args, "OO!:jproxy",
&pytarget,
&PyList_Type,
&interfaces)) {
return NULL;
}
jepThread = pyembed_get_jepthread();
if (!jepThread) {
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError, "Invalid JepThread pointer.");
}
return NULL;
}
env = jepThread->env;
cl = jepThread->classloader;
Py_UNBLOCK_THREADS;
clazz = (*env)->FindClass(env, "jep/Proxy");
Py_BLOCK_THREADS;
if (process_java_exception(env) || !clazz) {
return NULL;
}
if (newProxyMethod == 0) {
newProxyMethod =
(*env)->GetStaticMethodID(
env,
clazz,
"newProxyInstance",
"(JJLjep/Jep;Ljava/lang/ClassLoader;[Ljava/lang/String;)Ljava/lang/Object;");
if (process_java_exception(env) || !newProxyMethod) {
return NULL;
}
}
inum = (int) PyList_GET_SIZE(interfaces);
if (inum < 1) {
return PyErr_Format(PyExc_ValueError, "Empty interface list.");
}
// now convert string list to java array
classes = (*env)->NewObjectArray(env, (jsize) inum, JSTRING_TYPE, NULL);
if (process_java_exception(env) || !classes) {
return NULL;
}
for (i = 0; i < inum; i++) {
char *str;
jstring jstr;
PyObject *item;
item = PyList_GET_ITEM(interfaces, i);
if (!PyString_Check(item)) {
return PyErr_Format(PyExc_ValueError, "Item %zd not a string.", i);
}
str = PyString_AsString(item);
jstr = (*env)->NewStringUTF(env, (const char *) str);
(*env)->SetObjectArrayElement(env, classes, (jsize) i, jstr);
(*env)->DeleteLocalRef(env, jstr);
}
// do the deed
proxy = (*env)->CallStaticObjectMethod(env,
clazz,
newProxyMethod,
(jlong) (intptr_t) jepThread,
(jlong) (intptr_t) pytarget,
jepThread->caller,
cl,
classes);
if (process_java_exception(env) || !proxy) {
return NULL;
}
// make sure target doesn't get garbage collected
Py_INCREF(pytarget);
return pyjobject_new(env, proxy);
}
static PyObject* pyembed_set_print_stack(PyObject *self, PyObject *args)
{
JepThread *jepThread;
char *print = 0;
if (!PyArg_ParseTuple(args, "b:setPrintStack", &print)) {
return NULL;
}
jepThread = pyembed_get_jepthread();
if (!jepThread) {
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError, "Invalid JepThread pointer.");
}
return NULL;
}
if (print == 0) {
jepThread->printStack = 0;
} else {
jepThread->printStack = 1;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* pyembed_forname(PyObject *self, PyObject *args)
{
JNIEnv *env = NULL;
char *name;
jobject cl;
jclass objclazz;
jstring jstr;
JepThread *jepThread;
if (!PyArg_ParseTuple(args, "s", &name)) {
return NULL;
}
jepThread = pyembed_get_jepthread();
if (!jepThread) {
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError, "Invalid JepThread pointer.");
}
return NULL;
}
env = jepThread->env;
cl = jepThread->classloader;
LOAD_CLASS_METHOD(env, cl);
jstr = (*env)->NewStringUTF(env, (const char *) name);
if (process_java_exception(env) || !jstr) {
return NULL;
}
objclazz = (jclass) (*env)->CallObjectMethod(env,
cl,
loadClassMethod,
jstr);
if (process_java_exception(env) || !objclazz) {
return NULL;
}
return (PyObject *) pyjobject_new_class(env, objclazz);
}
static PyObject* pyembed_findclass(PyObject *self, PyObject *args)
{
JNIEnv *env = NULL;
char *name, *p;
jclass clazz;
JepThread *jepThread;
if (!PyArg_ParseTuple(args, "s", &name)) {
return NULL;
}
jepThread = pyembed_get_jepthread();
if (!jepThread) {
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError, "Invalid JepThread pointer.");
}
return NULL;
}
env = jepThread->env;
// replace '.' with '/'
// i'm told this is okay to do with unicode.
for (p = name; *p != '\0'; p++) {
if (*p == '.') {
*p = '/';
}
}
clazz = (*env)->FindClass(env, name);
if (process_java_exception(env)) {
return NULL;
}
return (PyObject *) pyjobject_new_class(env, clazz);
}
jobject pyembed_invoke_method(JNIEnv *env,
intptr_t _jepThread,
const char *cname,
jobjectArray args,
jintArray types)
{
PyObject *callable;
JepThread *jepThread;
jobject ret;
ret = NULL;
jepThread = (JepThread *) _jepThread;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return ret;
}
PyEval_AcquireThread(jepThread->tstate);
callable = PyDict_GetItemString(jepThread->globals, (char *) cname);
if (!callable) {
THROW_JEP(env, "Object was not found in the global dictionary.");
goto EXIT;
}
if (process_py_exception(env, 0)) {
goto EXIT;
}
ret = pyembed_invoke(env, callable, args, types);
EXIT:
PyEval_ReleaseThread(jepThread->tstate);
return ret;
}
// invoke object callable
// **** hold lock before calling ****
jobject pyembed_invoke(JNIEnv *env,
PyObject *callable,
jobjectArray args,
jintArray _types)
{
jobject ret;
int iarg, arglen;
jint *types; /* pinned primitive array */
jboolean isCopy;
PyObject *pyargs; /* a tuple */
PyObject *pyret;
types = NULL;
ret = NULL;
pyret = NULL;
if (!PyCallable_Check(callable)) {
THROW_JEP(env, "pyembed:invoke Invalid callable.");
return NULL;
}
// pin primitive array so we can get to it
types = (*env)->GetIntArrayElements(env, _types, &isCopy);
// first thing to do, convert java arguments to a python tuple
arglen = (*env)->GetArrayLength(env, args);
pyargs = PyTuple_New(arglen);
for (iarg = 0; iarg < arglen; iarg++) {
jobject val;
int typeid;
PyObject *pyval;
val = (*env)->GetObjectArrayElement(env, args, iarg);
if ((*env)->ExceptionCheck(env)) { /* careful, NULL is okay */
goto EXIT;
}
typeid = (int) types[iarg];
// now we know the type, convert and add to pyargs. we know
pyval = convert_jobject(env, val, typeid);
if ((*env)->ExceptionOccurred(env)) {
goto EXIT;
}
PyTuple_SET_ITEM(pyargs, iarg, pyval); /* steals */
if (val) {
(*env)->DeleteLocalRef(env, val);
}
} // for(iarg = 0; iarg < arglen; iarg++)
pyret = PyObject_CallObject(callable, pyargs);
if (process_py_exception(env, 0) || !pyret) {
goto EXIT;
}
// handles errors
ret = pyembed_box_py(env, pyret);
EXIT:
Py_XDECREF(pyargs);
Py_XDECREF(pyret);
if (types) {
(*env)->ReleaseIntArrayElements(env,
_types,
types,
JNI_ABORT);
(*env)->DeleteLocalRef(env, _types);
}
return ret;
}
void pyembed_eval(JNIEnv *env,
intptr_t _jepThread,
char *str)
{
PyObject *result;
JepThread *jepThread;
jepThread = (JepThread *) _jepThread;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return;
}
PyEval_AcquireThread(jepThread->tstate);
if (str == NULL) {
goto EXIT;
}
if (process_py_exception(env, 1)) {
goto EXIT;
}
result = PyRun_String(str, /* new ref */
Py_single_input,
jepThread->globals,
jepThread->globals);
// c programs inside some java environments may get buffered output
fflush(stdout);
fflush(stderr);
process_py_exception(env, 1);
Py_XDECREF(result);
EXIT:
PyEval_ReleaseThread(jepThread->tstate);
}
// returns 1 if finished, 0 if not, throws exception otherwise
int pyembed_compile_string(JNIEnv *env,
intptr_t _jepThread,
char *str)
{
PyObject *code;
int ret = -1;
JepThread *jepThread;
jepThread = (JepThread *) _jepThread;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return 0;
}
if (str == NULL) {
return 0;
}
PyEval_AcquireThread(jepThread->tstate);
code = Py_CompileString(str, "<stdin>", Py_single_input);
if (code != NULL) {
Py_DECREF(code);
ret = 1;
} else if (PyErr_ExceptionMatches(PyExc_SyntaxError)) {
PyErr_Clear();
ret = 0;
} else {
process_py_exception(env, 0);
}
PyEval_ReleaseThread(jepThread->tstate);
return ret;
}
intptr_t pyembed_create_module(JNIEnv *env,
intptr_t _jepThread,
char *str)
{
PyObject *module;
JepThread *jepThread;
intptr_t ret;
PyObject *key;
ret = 0;
jepThread = (JepThread *) _jepThread;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return 0;
}
if (str == NULL) {
return 0;
}
PyEval_AcquireThread(jepThread->tstate);
if (PyImport_AddModule(str) == NULL || process_py_exception(env, 1)) {
goto EXIT;
}
PyImport_AddModule(str);
module = PyImport_ImportModuleEx(str,
jepThread->globals,
jepThread->globals,
NULL); /* new ref */
key = PyString_FromString(str);
PyDict_SetItem(jepThread->globals,
key,
module); /* takes ownership */
Py_DECREF(key);
Py_DECREF(module);
if (process_py_exception(env, 0) || module == NULL) {
ret = 0;
} else {
ret = (intptr_t) module;
}
EXIT:
PyEval_ReleaseThread(jepThread->tstate);
return ret;
}
intptr_t pyembed_create_module_on(JNIEnv *env,
intptr_t _jepThread,
intptr_t _onModule,
char *str)
{
PyObject *module, *onModule;
JepThread *jepThread;
intptr_t ret;
PyObject *globals;
PyObject *key;
ret = 0;
globals = 0;
jepThread = (JepThread *) _jepThread;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return 0;
}
if (str == NULL) {
return 0;
}
PyEval_AcquireThread(jepThread->tstate);
onModule = (PyObject *) _onModule;
if (!PyModule_Check(onModule)) {
THROW_JEP(env, "Invalid onModule.");
goto EXIT;
}
globals = PyModule_GetDict(onModule);
Py_INCREF(globals);
if (PyImport_AddModule(str) == NULL || process_py_exception(env, 1)) {
goto EXIT;
}
PyImport_AddModule(str);
module = PyImport_ImportModuleEx(str, globals, globals, NULL); /* new ref */
key = PyString_FromString(str);
PyDict_SetItem(globals,
key,
module); /* ownership */
Py_DECREF(key);
Py_DECREF(module);
if (process_py_exception(env, 0) || module == NULL) {
ret = 0;
} else {
ret = (intptr_t) module;
}
EXIT:
Py_XDECREF(globals);
PyEval_ReleaseThread(jepThread->tstate);
return ret;
}
void pyembed_setloader(JNIEnv *env, intptr_t _jepThread, jobject cl)
{
jobject oldLoader = NULL;
JepThread *jepThread = (JepThread *) _jepThread;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return;
}