1 ///////////////////////////////////////////////////////
3 // VTT Technical Research Centre of Finland LTD //
4 // For internal use only. Do not redistribute. //
7 // Antton Tapani ext-antton.tapani@vtt.fi //
9 // Last modified by Antton Tapani 9.2016 //
11 ///////////////////////////////////////////////////////
17 jint throwException( JNIEnv *env, char *className, const char *message )
19 jclass exClass = (*env)->FindClass( env, className);
20 if (exClass == NULL) {
24 return (*env)->ThrowNew( env, exClass, message );
27 jint throwPythonException( JNIEnv *env, const char *message ) {
28 return throwException( env, PYTHON_EXCEPTION, message );
31 jint throwIllegalArgumentException( JNIEnv *env, const char *message ) {
32 return throwException( env, ILLEGAL_ARGUMENT_EXCEPTION, message );
35 PyObject* getModule(jlong contextID) {
36 return PyState_FindModule((PyModuleDef*) contextID);
37 // return PyImport_AddModule("__main__");
42 PyThreadState *main_ts = 0;
44 static JNIEnv *currentEnv = NULL;
45 jobject sclWriter = NULL;
48 writeToSCL(PyObject *self, PyObject *args)
50 if (currentEnv != NULL && sclWriter != NULL) {
51 JNIEnv *env = currentEnv;
55 if (!PyArg_ParseTuple(args, "u#", &what, &length))
56 return Py_BuildValue("");
59 jclass writerClass = (*env)->FindClass(env, WRITER_CLASS);
60 jmethodID writeMethod = (*env)->GetMethodID(env, writerClass, "write", "([CII)V");
61 jcharArray chars = (*env)->NewCharArray(env, (jsize)length);
63 (*env)->SetCharArrayRegion(env, chars, 0, length, what);
64 (*env)->CallVoidMethod(env, sclWriter, writeMethod, chars, 0, length);
68 return Py_BuildValue("");
71 static PyMethodDef sclWriterMethods[] = {
72 {"write", writeToSCL, METH_VARARGS, "Write something."},
77 JNIEXPORT jlong JNICALL Java_org_simantics_pythonlink_PythonContext_createContextImpl(JNIEnv *env, jobject thisObj) {
84 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "sclwriter", NULL, -1, sclWriterMethods, };
85 PyObject *m = PyModule_Create(&moduledef);
87 if (m == NULL) throwException(env, PYTHON_EXCEPTION, "Failed to create SCL writer module");
88 PySys_SetObject("stdout", m);
89 PySys_SetObject("stderr", m);
92 hasNumpy = _import_array();
93 hasNumpy = hasNumpy != -1;
94 main_ts = PyEval_SaveThread();
97 sprintf(name, "SCL_%d", ++moduleCount);
99 PyEval_RestoreThread(main_ts);
102 PyModuleDef *modDef = malloc(sizeof(PyModuleDef));
103 memset(modDef, 0, sizeof(PyModuleDef));
104 modDef->m_name = strdup(name);
105 modDef->m_doc = NULL;
108 module = PyModule_Create(modDef);
110 PyState_AddModule(module, modDef);
113 PyObject *builtin = PyImport_AddModule("builtins");
114 PyObject *dict = PyModule_GetDict(module);
115 PyDict_SetItemString(dict, "__builtin__", builtin);
116 PyDict_SetItemString(dict, "__builtins__", builtin);
118 return (jlong)modDef;
123 JNIEXPORT void JNICALL Java_org_simantics_pythonlink_PythonContext_deleteContextImpl(JNIEnv *env, jobject thisObj, jlong contextID) {
124 PyModuleDef *modDef = (PyModuleDef*)contextID;
126 PyEval_RestoreThread(main_ts);
127 module = PyState_FindModule(modDef);
129 PyState_RemoveModule(modDef);
130 free((char*)modDef->m_name);
135 PyObject *getPythonBool(jboolean value) {
144 PyObject *getPythonString(JNIEnv *env, jstring string) {
145 jsize len = (*env)->GetStringLength(env, string);
146 const jchar *chars = (*env)->GetStringChars(env, string, NULL);
148 PyObject *value = PyUnicode_DecodeUTF16((char*)chars, 2*len, NULL, NULL);
150 (*env)->ReleaseStringChars(env, string, chars);
154 PyObject *getPythonStringList(JNIEnv *env, jobjectArray value) {
155 jsize nitems = (*env)->GetArrayLength(env, value);
156 jint *values = (*env)->GetIntArrayElements(env, value, NULL);
157 jclass stringClass = (*env)->FindClass(env, STRING_CLASS);
160 PyObject *result = PyList_New(nitems);
161 for (i = 0; i < nitems; i++) {
162 jobject item = (*env)->GetObjectArrayElement(env, value, i);
163 if (item != NULL && (*env)->IsInstanceOf(env, item, stringClass)) {
164 PyList_SetItem(result, i, getPythonString(env, (jstring)item));
167 PyList_SetItem(result, i, Py_None);
171 (*env)->ReleaseIntArrayElements(env, value, values, JNI_ABORT);
175 PyObject *getPythonBooleanList(JNIEnv *env, jbooleanArray value) {
176 jsize nitems = (*env)->GetArrayLength(env, value);
177 jboolean *values = (*env)->GetBooleanArrayElements(env, value, NULL);
180 PyObject *result = PyList_New(nitems);
181 for (i = 0; i < nitems; i++) {
182 PyList_SetItem(result, i, getPythonBool(values[i]));
185 (*env)->ReleaseBooleanArrayElements(env, value, values, JNI_ABORT);
189 PyObject *getPythonByteArray(JNIEnv *env, jbyteArray value) {
190 jint len = (*env)->GetArrayLength(env, value);
191 jbyte *values = (*env)->GetByteArrayElements(env, value, NULL);
193 PyObject *result = PyByteArray_FromStringAndSize(values, len);
195 (*env)->ReleaseByteArrayElements(env, value, values, JNI_ABORT);
199 PyObject *getPythonIntegerList(JNIEnv *env, jintArray value) {
200 jsize nitems = (*env)->GetArrayLength(env, value);
201 jint *values = (*env)->GetIntArrayElements(env, value, NULL);
204 PyObject *result = PyList_New(nitems);
205 for (i = 0; i < nitems; i++) {
206 PyList_SetItem(result, i, PyLong_FromLong(values[i]));
209 (*env)->ReleaseIntArrayElements(env, value, values, JNI_ABORT);
213 PyObject *getPythonLongList(JNIEnv *env, jlongArray value) {
214 jsize nitems = (*env)->GetArrayLength(env, value);
215 jlong *values = (*env)->GetLongArrayElements(env, value, NULL);
218 PyObject *result = PyList_New(nitems);
219 for (i = 0; i < nitems; i++) {
220 PyList_SetItem(result, i, PyLong_FromLongLong(values[i]));
223 (*env)->ReleaseLongArrayElements(env, value, values, JNI_ABORT);
227 PyObject *getPythonFloatList(JNIEnv *env, jfloatArray value) {
228 jsize nitems = (*env)->GetArrayLength(env, value);
229 float *values = (*env)->GetFloatArrayElements(env, value, NULL);
232 PyObject *result = PyList_New(nitems);
233 for (i = 0; i < nitems; i++) {
234 PyList_SetItem(result, i, PyFloat_FromDouble((double)values[i]));
237 (*env)->ReleaseFloatArrayElements(env, value, values, JNI_ABORT);
241 PyObject *getPythonDoubleList(JNIEnv *env, jdoubleArray value) {
242 jsize nitems = (*env)->GetArrayLength(env, value);
243 double *values = (*env)->GetDoubleArrayElements(env, value, NULL);
246 PyObject *result = PyList_New(nitems);
247 for (i = 0; i < nitems; i++) {
248 PyList_SetItem(result, i, PyFloat_FromDouble(values[i]));
251 (*env)->ReleaseDoubleArrayElements(env, value, values, JNI_ABORT);
255 PyObject *getPythonNDArray(JNIEnv *env, jobject value) {
256 jclass ndarrayClass = (*env)->FindClass(env, NDARRAY_CLASS);
257 jmethodID dimsMethod = (*env)->GetMethodID(env, ndarrayClass, "dims", "()[I");
258 jmethodID getValuesMethod = (*env)->GetMethodID(env, ndarrayClass, "getValues", "()[D");
260 jintArray jdims = (*env)->CallObjectMethod(env, value, dimsMethod);
261 jsize ndims = (*env)->GetArrayLength(env, jdims);
262 jint *dims = (*env)->GetIntArrayElements(env, jdims, NULL);
264 jdoubleArray jvalues = (*env)->CallObjectMethod(env, value, getValuesMethod);
265 jsize len = (*env)->GetArrayLength(env, jvalues);
266 jdouble *values = (*env)->GetDoubleArrayElements(env, jvalues, NULL);
268 npy_intp *pyDims = (npy_intp*)malloc(ndims * sizeof(npy_intp));
270 jint i, nelem = ndims > 0 ? 1 : 0;
271 for (i = 0; i < ndims; i++) {
276 len = min(len, nelem);
279 PyObject *array = PyArray_EMPTY(ndims, pyDims, NPY_DOUBLE, 0);
280 double *data = (double *)PyArray_DATA((PyArrayObject*)array);
282 memcpy(data, values, len * sizeof(double));
286 (*env)->ReleaseDoubleArrayElements(env, jvalues, values, JNI_ABORT);
287 (*env)->ReleaseIntArrayElements(env, jdims, dims, JNI_ABORT);
293 PyObject *getPythonBooleanObject(JNIEnv *env, jobject object, jobject binding) {
294 jclass bindingClass = (*env)->FindClass(env, BOOLEANBINDING_CLASS);
295 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue_", "(L" OBJECT_CLASS ";)Z");
297 jboolean bvalue = (*env)->CallBooleanMethod(env, binding, getValueMethod, object);
298 return getPythonBool(bvalue);
301 PyObject *getPythonByteObject(JNIEnv *env, jobject object, jobject binding) {
302 jclass bindingClass = (*env)->FindClass(env, BYTEBINDING_CLASS);
303 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue_", "(L" OBJECT_CLASS ";)B");
305 jbyte v = (*env)->CallByteMethod(env, binding, getValueMethod, object);
306 return PyLong_FromLong(v);
309 PyObject *getPythonIntegerObject(JNIEnv *env, jobject object, jobject binding) {
310 jclass bindingClass = (*env)->FindClass(env, INTEGERBINDING_CLASS);
311 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue_", "(L" OBJECT_CLASS ";)I");
313 jint v = (*env)->CallIntMethod(env, binding, getValueMethod, object);
314 return PyLong_FromLong(v);
317 PyObject *getPythonLongObject(JNIEnv *env, jobject object, jobject binding) {
318 jclass bindingClass = (*env)->FindClass(env, LONGBINDING_CLASS);
319 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue_", "(L" OBJECT_CLASS ";)J");
321 jlong v = (*env)->CallLongMethod(env, binding, getValueMethod, object);
322 return PyLong_FromLongLong(v);
325 PyObject *getPythonFloatObject(JNIEnv *env, jobject object, jobject binding) {
326 jclass bindingClass = (*env)->FindClass(env, FLOATBINDING_CLASS);
327 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue_", "(L" OBJECT_CLASS ";)F");
329 jfloat v = (*env)->CallFloatMethod(env, binding, getValueMethod, object);
330 return PyFloat_FromDouble(v);
333 PyObject *getPythonDoubleObject(JNIEnv *env, jobject object, jobject binding) {
334 jclass bindingClass = (*env)->FindClass(env, DOUBLEBINDING_CLASS);
335 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue_", "(L" OBJECT_CLASS ";)D");
337 jdouble v = (*env)->CallDoubleMethod(env, binding, getValueMethod, object);
338 return PyFloat_FromDouble(v);
341 PyObject *getPythonStringObject(JNIEnv *env, jobject object, jobject binding) {
342 jclass bindingClass = (*env)->FindClass(env, STRINGBINDING_CLASS);
343 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue", "(L" OBJECT_CLASS ";)L" STRING_CLASS ";");
345 jobject string = (*env)->CallObjectMethod(env, binding, getValueMethod, object);
346 jsize len = (*env)->GetStringLength(env, string);
347 const jchar *chars = (*env)->GetStringChars(env, string, NULL);
349 PyObject *value = PyUnicode_DecodeUTF16((char*)chars, 2*len, NULL, NULL);
351 (*env)->ReleaseStringChars(env, string, chars);
355 PyObject *getPythonRecordObject(JNIEnv *env, jobject object, jobject binding) {
356 jclass bindingClass = (*env)->FindClass(env, RECORDBINDING_CLASS);
357 jmethodID typeMethod = (*env)->GetMethodID(env, bindingClass, "type", "()L" RECORDTYPE_CLASS ";");
358 jmethodID getComponent = (*env)->GetMethodID(env, bindingClass, "getComponent", "(L" OBJECT_CLASS ";I)L" OBJECT_CLASS ";");
359 jmethodID getComponentBinding = (*env)->GetMethodID(env, bindingClass, "getComponentBinding", "(I)L" BINDING_CLASS ";");
361 jclass recordType = (*env)->FindClass(env, RECORDTYPE_CLASS);
362 jmethodID getTypeComponent = (*env)->GetMethodID(env, recordType, "getComponent", "(I)L" COMPONENT_CLASS ";");
363 jmethodID getComponentCount = (*env)->GetMethodID(env, recordType, "getComponentCount", "()I");
365 jclass componentClass = (*env)->FindClass(env, COMPONENT_CLASS);
366 jfieldID nameField = (*env)->GetFieldID(env, componentClass, "name", "L" STRING_CLASS ";");
368 jobject type = (*env)->CallObjectMethod(env, binding, typeMethod);
369 jint n = (*env)->CallIntMethod(env, type, getComponentCount);
372 PyObject *result = PyDict_New();
373 for (i = 0; i < n; i++) {
374 jobject recordTypeComponent = (*env)->CallObjectMethod(env, type, getComponent, i);
375 jstring fieldName = (jstring)(*env)->GetObjectField(env, recordTypeComponent, nameField);
376 jobject componentObject = (*env)->CallObjectMethod(env, binding, getComponent, object, i);
377 jobject componentBinding = (*env)->CallObjectMethod(env, binding, getComponentBinding, i);
379 PyObject *item = getPythonObject(env, componentObject, componentBinding);
380 PyDict_SetItem(result, getPythonString(env, fieldName), item);
386 PyObject *getPythonArrayObject(JNIEnv *env, jobject object, jobject binding) {
387 jclass bindingClass = (*env)->FindClass(env, ARRAYBINDING_CLASS);
388 jmethodID componentBindingMethod = (*env)->GetMethodID(env, bindingClass, "getComponentBinding", "()L" BINDING_CLASS ";");
389 jmethodID sizeMethod = (*env)->GetMethodID(env, bindingClass, "size", "(L" OBJECT_CLASS ";)I");
390 jmethodID getMethod = (*env)->GetMethodID(env, bindingClass, "get", "(L" OBJECT_CLASS ";I)L" OBJECT_CLASS ";");
392 jobject componentBinding = (*env)->CallObjectMethod(env, binding, componentBindingMethod);
394 jint size = (*env)->CallIntMethod(env, binding, sizeMethod, object);
396 PyObject *result = PyList_New(size);
399 for (i = 0; i < size; i++) {
400 jobject item = (*env)->CallObjectMethod(env, binding, getMethod, object, i);
402 PyList_SetItem(result, i, getPythonObject(env, item, componentBinding));
404 PyList_SetItem(result, i, Py_None);
410 PyObject *getPythonMapObject(JNIEnv *env, jobject object, jobject binding) {
411 jclass objectClass = (*env)->FindClass(env, OBJECT_CLASS);
412 jclass bindingClass = (*env)->FindClass(env, MAPBINDING_CLASS);
413 jmethodID getKeyBindingMethod = (*env)->GetMethodID(env, bindingClass, "getKeyBinding", "()L" BINDING_CLASS ";");
414 jmethodID getValueBindingMethod = (*env)->GetMethodID(env, bindingClass, "getValueBinding", "()L" BINDING_CLASS ";");
415 jmethodID sizeMethod = (*env)->GetMethodID(env, bindingClass, "size", "(L" OBJECT_CLASS ";)I");
416 jmethodID getAllMethod = (*env)->GetMethodID(env, bindingClass, "getAll", "(L" OBJECT_CLASS ";[L" OBJECT_CLASS ";[L" OBJECT_CLASS ";)V");
418 jobject keyBinding = (*env)->CallObjectMethod(env, binding, getKeyBindingMethod);
419 jobject valueBinding = (*env)->CallObjectMethod(env, binding, getValueBindingMethod);
421 jint size = (*env)->CallIntMethod(env, binding, sizeMethod, object);
422 jobjectArray keys = (*env)->NewObjectArray(env, size, objectClass, NULL);
423 jobjectArray values = (*env)->NewObjectArray(env, size, objectClass, NULL);
425 PyObject *result = PyDict_New();
428 (*env)->CallVoidMethod(env, binding, getAllMethod, object, keys, values);
430 for (i = 0; i < size; i++) {
431 jobject key = (*env)->GetObjectArrayElement(env, keys, i);
432 jobject item = (*env)->GetObjectArrayElement(env, values, i);
433 PyDict_SetItem(result, getPythonObject(env, key, keyBinding), getPythonObject(env, item, valueBinding));
436 (*env)->DeleteLocalRef(env, keys);
437 (*env)->DeleteLocalRef(env, values);
442 PyObject *getPythonOptionalObject(JNIEnv *env, jobject object, jobject binding) {
443 jclass bindingClass = (*env)->FindClass(env, OPTIONALBINDING_CLASS);
444 jmethodID hasValueMethod = (*env)->GetMethodID(env, bindingClass, "hasValue", "(L" OBJECT_CLASS ";)Z");
446 jboolean hasValue = (*env)->CallBooleanMethod(env, binding, hasValueMethod, object);
449 jmethodID componentBindingMethod = (*env)->GetMethodID(env, bindingClass, "getComponentBinding", "()L" BINDING_CLASS ";");
450 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "hasValue", "(L" OBJECT_CLASS ";)L" OBJECT_CLASS ";");
452 jobject componentBinding = (*env)->CallObjectMethod(env, binding, componentBindingMethod);
453 jobject value = (*env)->CallObjectMethod(env, binding, getValueMethod, object);
455 return getPythonObject(env, value, componentBinding);
462 PyObject *getPythonUnionObject(JNIEnv *env, jobject object, jobject binding) {
463 jclass bindingClass = (*env)->FindClass(env, UNIONBINDING_CLASS);
464 jmethodID typeMethod = (*env)->GetMethodID(env, bindingClass, "type", "()L" RECORDTYPE_CLASS ";");
465 jmethodID getTagMethod = (*env)->GetMethodID(env, bindingClass, "getTag", "(L" OBJECT_CLASS ";)I");
466 jmethodID getValueMethod = (*env)->GetMethodID(env, bindingClass, "getValue", "(L" OBJECT_CLASS ";)L" OBJECT_CLASS ";");
467 jmethodID getComponentBinding = (*env)->GetMethodID(env, bindingClass, "getComponentBinding", "(I)L" BINDING_CLASS ";");
469 jclass unionType = (*env)->FindClass(env, UNIONTYPE_CLASS);
470 jmethodID getTypeComponent = (*env)->GetMethodID(env, unionType, "getComponent", "(I)L" COMPONENT_CLASS ";");
472 jclass componentClass = (*env)->FindClass(env, COMPONENT_CLASS);
473 jfieldID nameField = (*env)->GetFieldID(env, componentClass, "name", "L" STRING_CLASS ";");
475 jint tag = (*env)->CallIntMethod(env, binding, getTagMethod, object);
476 jobject value = (*env)->CallObjectMethod(env, binding, getValueMethod, object);
478 jobject type = (*env)->CallObjectMethod(env, binding, typeMethod);
479 jobject typeComponent = (*env)->CallObjectMethod(env, type, getTypeComponent, tag);
480 jstring compName = (*env)->GetObjectField(env, typeComponent, nameField);
482 jobject componentBinding = (*env)->CallObjectMethod(env, binding, getComponentBinding, tag);
484 PyObject *result = PyTuple_New(2);
485 PyTuple_SetItem(result, 0, getPythonString(env, compName));
486 PyTuple_SetItem(result, 1, getPythonObject(env, value, componentBinding));
491 PyObject *getPythonVariantObject(JNIEnv *env, jobject object, jobject binding) {
492 jclass bindingClass = (*env)->FindClass(env, VARIANTBINDING_CLASS);
493 jmethodID getContentMethod = (*env)->GetMethodID(env, bindingClass, "getContent", "(L" OBJECT_CLASS ";)L" OBJECT_CLASS ";");
494 jmethodID getContentBindingMethod = (*env)->GetMethodID(env, bindingClass, "getContentBinding", "(L" OBJECT_CLASS ";)L" BINDING_CLASS ";");
496 jobject content = (*env)->CallObjectMethod(env, binding, getContentMethod, object);
497 jobject contentBinding = (*env)->CallObjectMethod(env, binding, getContentBindingMethod, object);
499 return getPythonObject(env, content, contentBinding);
502 PyObject *getPythonObject(JNIEnv *env, jobject value, jobject binding) {
503 jclass booleanBinding = (*env)->FindClass(env, BOOLEANBINDING_CLASS);
504 jclass byteBinding = (*env)->FindClass(env, BYTEBINDING_CLASS);
505 jclass integerBinding = (*env)->FindClass(env, INTEGERBINDING_CLASS);
506 jclass longBinding = (*env)->FindClass(env, LONGBINDING_CLASS);
507 jclass floatBinding = (*env)->FindClass(env, FLOATBINDING_CLASS);
508 jclass doubleBinding = (*env)->FindClass(env, DOUBLEBINDING_CLASS);
509 jclass stringBinding = (*env)->FindClass(env, STRINGBINDING_CLASS);
510 jclass recordBinding = (*env)->FindClass(env, RECORDBINDING_CLASS);
511 jclass arrayBinding = (*env)->FindClass(env, ARRAYBINDING_CLASS);
512 jclass mapBinding = (*env)->FindClass(env, MAPBINDING_CLASS);
513 jclass optionalBinding = (*env)->FindClass(env, OPTIONALBINDING_CLASS);
514 jclass untionBinding = (*env)->FindClass(env, UNIONBINDING_CLASS);
515 jclass variantBinding = (*env)->FindClass(env, VARIANTBINDING_CLASS);
520 if ((*env)->IsInstanceOf(env, binding, booleanBinding)) {
521 return getPythonBooleanObject(env, value, binding);
523 else if ((*env)->IsInstanceOf(env, binding, byteBinding)) {
524 return getPythonByteObject(env, value, binding);
526 else if ((*env)->IsInstanceOf(env, binding, integerBinding)) {
527 return getPythonIntegerObject(env, value, binding);
529 else if ((*env)->IsInstanceOf(env, binding, longBinding)) {
530 return getPythonLongObject(env, value, binding);
532 else if ((*env)->IsInstanceOf(env, binding, floatBinding)) {
533 return getPythonFloatObject(env, value, binding);
535 else if ((*env)->IsInstanceOf(env, binding, doubleBinding)) {
536 return getPythonDoubleObject(env, value, binding);
538 else if ((*env)->IsInstanceOf(env, binding, stringBinding)) {
539 return getPythonStringObject(env, value, binding);
541 else if ((*env)->IsInstanceOf(env, binding, recordBinding)) {
542 return getPythonRecordObject(env, value, binding);
544 else if ((*env)->IsInstanceOf(env, binding, arrayBinding)) {
545 return getPythonArrayObject(env, value, binding);
547 else if ((*env)->IsInstanceOf(env, binding, mapBinding)) {
548 return getPythonMapObject(env, value, binding);
550 else if ((*env)->IsInstanceOf(env, binding, optionalBinding)) {
551 return getPythonOptionalObject(env, value, binding);
553 else if ((*env)->IsInstanceOf(env, binding, untionBinding)) {
554 return getPythonUnionObject(env, value, binding);
556 else if ((*env)->IsInstanceOf(env, binding, variantBinding)) {
557 return getPythonVariantObject(env, value, binding);
564 void setPythonVariable(PyObject *module, PyObject *name, PyObject *value) {
566 PyDict_SetItem(PyModule_GetDict(module), name, value);
573 static npy_intp nContiguous(int d, int nd, npy_intp *strides, npy_intp *dims, npy_intp *ncont) {
579 npy_intp n = nContiguous(d+1, nd, strides, dims, ncont);
580 ncont[d] = n > 0 && strides[d] == sizeof(double) * n ? dims[d] * n : 0;
585 static void copyDoubleArrayValues(JNIEnv *env, jdoubleArray array, double *data, npy_intp *offset, int d, int nd, npy_intp *strides, npy_intp *dims, npy_intp *ncont) {
587 (*env)->SetDoubleArrayRegion(env, array, (jint)*offset, (jint)ncont[d], data);
592 for (i = 0; i < dims[d]; i++) {
593 copyDoubleArrayValues(env, array, (double*)((char*)data + strides[d] * i), offset, d+1, nd, strides, dims, ncont);
598 jobject pythonBoolAsBooleanObject(JNIEnv *env, PyObject *value) {
599 jclass booleanClass = (*env)->FindClass(env, "java/lang/Boolean");
600 jmethodID valueOfMethod = (*env)->GetStaticMethodID(env, booleanClass, "valueOf", "(Z)Ljava/lang/Boolean;");
602 return (*env)->CallStaticObjectMethod(env, booleanClass, valueOfMethod, (jboolean)(value == Py_True));
605 jobject pythonLongAsLongObject(JNIEnv *env, PyObject *value) {
606 jclass longClass = (*env)->FindClass(env, "java/lang/Long");
607 jmethodID valueOfMethod = (*env)->GetStaticMethodID(env, longClass, "valueOf", "(J)Ljava/lang/Long;");
609 return (*env)->CallStaticObjectMethod(env, longClass, valueOfMethod, PyLong_AsLongLong(value));
612 jobject pythonFloatAsDoubleObject(JNIEnv *env, PyObject *value) {
613 jclass doubleClass = (*env)->FindClass(env, "java/lang/Double");
614 jmethodID valueOfMethod = (*env)->GetStaticMethodID(env, doubleClass, "valueOf", "(D)Ljava/lang/Double;");
616 return (*env)->CallStaticObjectMethod(env, doubleClass, valueOfMethod, PyFloat_AsDouble(value));
619 jobject pythonByteArrayAsByteArray(JNIEnv *env, PyObject *value) {
620 Py_ssize_t size = PyByteArray_Size(value);
621 jbyteArray result = (*env)->NewByteArray(env, (jsize)size);
622 char *bytes = PyByteArray_AsString(value);
624 (*env)->SetByteArrayRegion(env, result, 0, size, bytes);
629 jstring pythonStringAsJavaString(JNIEnv *env, PyObject *string) {
630 PyObject *utf16Value = PyUnicode_AsUTF16String(string);
631 Py_ssize_t len = PyBytes_Size(utf16Value) / 2;
632 char *bytes = PyBytes_AsString(utf16Value);
634 // Create Java string, skipping the byte order mark in the beginning
635 jstring result = (*env)->NewString(env, (jchar *)bytes + 1, (jsize)min(len, JAVA_MAXINT) - 1);
637 Py_XDECREF(utf16Value);
642 jobjectArray pythonSequenceAsStringArray(JNIEnv *env, PyObject *seq) {
643 Py_ssize_t len = PySequence_Size(seq);
644 jsize jlen = (jsize)min(len, JAVA_MAXINT);
645 jobjectArray array = (*env)->NewObjectArray(env, jlen, (*env)->FindClass(env, STRING_CLASS), NULL);
649 for (i = 0; i < jlen; i++) {
650 PyObject *item = PySequence_GetItem(seq, i);
651 if (PyUnicode_Check(item)) {
652 jstring value = pythonStringAsJavaString(env, item);
653 (*env)->SetObjectArrayElement(env, array, i, value);
656 throwPythonException(env, "List item not a string");
664 jdoubleArray pythonSequenceAsDoubleArray(JNIEnv *env, PyObject *seq) {
665 Py_ssize_t len = PySequence_Size(seq);
666 jsize jlen = (jsize)min(len, JAVA_MAXINT);
667 jdoubleArray array = (*env)->NewDoubleArray(env, jlen);
671 for (i = 0; i < jlen; i++) {
672 PyObject *item = PySequence_GetItem(seq, i);
673 if (PyFloat_Check(item)) {
674 double value = PyFloat_AsDouble(item);
675 (*env)->SetDoubleArrayRegion(env, array, i, 1, &value);
678 throwPythonException(env, "List item not a floating point value");
686 jobject pythonObjectAsObject(JNIEnv *env, PyObject *value) {
687 if (PyBool_Check(value))
688 return pythonBoolAsBooleanObject(env, value);
689 else if (PyLong_Check(value))
690 return pythonLongAsLongObject(env, value);
691 else if (PyFloat_Check(value))
692 return pythonFloatAsDoubleObject(env, value);
693 else if (PyUnicode_Check(value))
694 return pythonStringAsJavaString(env, value);
695 else if (PyByteArray_Check(value))
696 return pythonByteArrayAsByteArray(env, value);
697 else if (PyDict_Check(value))
698 return pythonDictionaryAsMap(env, value);
699 else if (hasNumpy && PyArray_Check(value))
700 return pythonArrayAsNDArray(env, (PyArrayObject *)value);
701 else if (PySequence_Check(value))
702 return pythonSequenceAsObjectArray(env, value);
707 jobjectArray pythonSequenceAsObjectArray(JNIEnv *env, PyObject *seq) {
708 Py_ssize_t len = PySequence_Size(seq);
709 jsize jlen = (jsize)min(len, JAVA_MAXINT);
710 jobjectArray array = (*env)->NewObjectArray(env, jlen, (*env)->FindClass(env, OBJECT_CLASS), NULL);
714 for (i = 0; i < jlen; i++) {
715 PyObject *item = PySequence_GetItem(seq, i);
716 jobject object = pythonObjectAsObject(env, item);
717 (*env)->SetObjectArrayElement(env, array, i, object);
723 jbooleanArray pythonSequenceAsBooleanArray(JNIEnv *env, PyObject *seq) {
724 Py_ssize_t len = PySequence_Size(seq);
725 jsize jlen = (jsize)min(len, JAVA_MAXINT);
726 jbooleanArray array = (*env)->NewBooleanArray(env, jlen);
730 for (i = 0; i < jlen; i++) {
731 PyObject *item = PySequence_GetItem(seq, i);
732 if (PyBool_Check(item)) {
733 jboolean value = item == Py_True;
734 (*env)->SetBooleanArrayRegion(env, array, i, 1, &value);
737 throwPythonException(env, "List item not a boolean");
745 jintArray pythonSequenceAsIntegerArray(JNIEnv *env, PyObject *seq) {
746 Py_ssize_t len = PySequence_Size(seq);
747 jsize jlen = (jsize)min(len, JAVA_MAXINT);
748 jintArray array = (*env)->NewIntArray(env, jlen);
752 for (i = 0; i < jlen; i++) {
753 PyObject *item = PySequence_GetItem(seq, i);
754 if (PyLong_Check(item)) {
755 jint value = PyLong_AsLong(item);
756 (*env)->SetIntArrayRegion(env, array, i, 1, &value);
759 throwPythonException(env, "List item not an integer");
767 jlongArray pythonSequenceAsLongArray(JNIEnv *env, PyObject *seq) {
768 Py_ssize_t len = PySequence_Size(seq);
769 jsize jlen = (jsize)min(len, JAVA_MAXINT);
770 jlongArray array = (*env)->NewLongArray(env, jlen);
774 for (i = 0; i < jlen; i++) {
775 PyObject *item = PySequence_GetItem(seq, i);
776 if (PyLong_Check(item)) {
777 jlong value = PyLong_AsLongLong(item);
778 (*env)->SetLongArrayRegion(env, array, i, 1, &value);
781 throwPythonException(env, "List item not an integer");
789 jobject pythonArrayAsNDArray(JNIEnv *env, PyArrayObject *array) {
790 jclass ndarrayClass = (*env)->FindClass(env, NDARRAY_CLASS);
791 jmethodID constructor = (*env)->GetMethodID(env, ndarrayClass, "<init>", "([I[D)V");
793 int ndims = PyArray_NDIM(array);
794 npy_intp *dims = PyArray_DIMS(array);
796 npy_intp len = PyArray_Size((PyObject*)array);
797 double *values = (double*)PyArray_DATA(array);
799 jboolean isFortran = PyArray_ISFORTRAN(array) != 0;
803 if (len > JAVA_MAXINT) {
804 throwPythonException(env, "Array too large");
809 jintArray jdims = (*env)->NewIntArray(env, ndims);
810 jdoubleArray jvalues = (*env)->NewDoubleArray(env, (jsize)len);
812 for (i = 0; i < ndims; i++) {
813 jint dim = (jint)dims[i];
814 (*env)->SetIntArrayRegion(env, jdims, i, 1, &dim);
817 if (PyArray_IS_C_CONTIGUOUS(array)) {
818 (*env)->SetDoubleArrayRegion(env, jvalues, 0, (jsize)len, values);
822 npy_intp *strides = PyArray_STRIDES(array);
823 npy_intp *ncont = (npy_intp*)malloc((ndims + 1) * sizeof(npy_intp));
824 nContiguous(0, ndims, strides, dims, ncont);
825 copyDoubleArrayValues(env, jvalues, values, &offset, 0, ndims, strides, dims, ncont);
829 return (*env)->NewObject(env, ndarrayClass, constructor, jdims, jvalues, isFortran);
833 jobject pythonDictionaryAsMap(JNIEnv *env, PyObject *dict) {
834 jclass hashmapClass = (*env)->FindClass(env, "java/util/HashMap");
835 jmethodID constructor = (*env)->GetMethodID(env, hashmapClass, "<init>", "(I)V");
836 jmethodID putMethod = (*env)->GetMethodID(env, hashmapClass, "put", "(L" OBJECT_CLASS ";L" OBJECT_CLASS ";)L" OBJECT_CLASS ";");
838 Py_ssize_t size = PyDict_Size(dict);
839 jobject map = (*env)->NewObject(env, hashmapClass, constructor, (jint)size);
841 PyObject *key, *value;
844 while (PyDict_Next(dict, &pos, &key, &value)) {
845 jobject keyObject = pythonObjectAsObject(env, key);
846 jobject valueObject = pythonObjectAsObject(env, value);
847 (*env)->CallObjectMethod(env, map, putMethod, keyObject, valueObject);
853 #define DEF_SETTER(typename, jtype, j2py) \
854 JNIEXPORT void JNICALL \
855 Java_org_simantics_pythonlink_PythonContext_setPython##typename \
857 JNIEnv *env, jobject thisObj, jlong contextID, jstring variableName, \
859 PyObject *module = getModule(contextID); \
861 PyEval_RestoreThread(main_ts); \
862 setPythonVariable(module, getPythonString(env, variableName), \
864 PyEval_SaveThread(); \
867 #define getPythonBoolean(env, value) getPythonBool(value)
868 #define getPythonLong(env, value) PyLong_FromLongLong(value)
869 #define getPythonDouble(env, value) PyFloat_FromDouble(value)
871 DEF_SETTER(Boolean, jboolean, getPythonBoolean)
872 DEF_SETTER(BooleanArray, jbooleanArray, getPythonBooleanList)
873 DEF_SETTER(Long, jlong, getPythonLong)
874 DEF_SETTER(IntegerArray, jintArray, getPythonIntegerList)
875 DEF_SETTER(LongArray, jlongArray, getPythonLongList)
876 DEF_SETTER(Double, jdouble, getPythonDouble)
877 DEF_SETTER(FloatArray, jfloatArray, getPythonFloatList)
878 DEF_SETTER(DoubleArray, jdoubleArray, getPythonDoubleList)
879 DEF_SETTER(String, jstring, getPythonString)
880 DEF_SETTER(StringArray, jobjectArray, getPythonStringList)
882 JNIEXPORT void JNICALL
883 Java_org_simantics_pythonlink_PythonContext_setPythonNDArrayVariableImpl(
884 JNIEnv *env, jobject thisObj, jlong contextID, jstring variableName,
886 PyObject *module = getModule(contextID);
889 throwPythonException(env, "Importing numpy failed");
893 PyEval_RestoreThread(main_ts);
895 PyObject *pythonName = getPythonString(env, variableName);
896 PyObject *val = getPythonNDArray(env, value);
898 setPythonVariable(module, pythonName, val);
903 JNIEXPORT void JNICALL
904 Java_org_simantics_pythonlink_PythonContext_setPythonVariantVariableImpl(
905 JNIEnv *env, jobject thisObj, jlong contextID, jstring variableName,
906 jobject value, jobject binding) {
907 PyObject *module = getModule(contextID);
909 PyEval_RestoreThread(main_ts);
910 setPythonVariable(module, getPythonString(env, variableName),
911 getPythonObject(env, value, binding));
915 JNIEXPORT jint JNICALL
916 Java_org_simantics_pythonlink_PythonContext_executePythonStatementImpl(
917 JNIEnv *env, jobject thisObj, jlong contextID, jstring statement) {
918 PyObject *module = getModule(contextID);
920 const char *utfchars = (*env)->GetStringUTFChars(env, statement, NULL);
922 PyEval_RestoreThread(main_ts);
925 jclass sclReportingWriterClass = (*env)->FindClass(env, SCL_REPORTING_WRITER_CLASS);
926 jmethodID constructor = (*env)->GetMethodID(env, sclReportingWriterClass, "<init>", "()V");
927 jmethodID flushMethod = (*env)->GetMethodID(env, sclReportingWriterClass, "flush", "()V");
931 globals = PyModule_GetDict(module);
934 if (sclReportingWriterClass && constructor)
935 sclWriter = (*env)->NewObject(env, sclReportingWriterClass, constructor);
940 PyObject *result = PyRun_String(utfchars, Py_file_input, globals, globals);
942 PyObject *exceptionType = PyErr_Occurred();
943 if (exceptionType != NULL) {
944 PyObject *exception, *traceback;
945 PyErr_Fetch(&exceptionType, &exception, &traceback);
948 PyObject *tracebackModule = PyImport_ImportModule("traceback");
949 if (tracebackModule != NULL) {
950 PyObject *formatExc = PyDict_GetItemString(PyModule_GetDict(tracebackModule), "format_exception");
951 if (formatExc != NULL) {
952 PyObject *args = PyTuple_Pack(3, exceptionType, exception, traceback);
953 PyObject *message = PyObject_CallObject(formatExc, args);
954 if (message != NULL) {
955 PyObject *emptyStr = PyUnicode_FromString("");
956 PyObject *joined = PyUnicode_Join(emptyStr, message);
957 char *messageStr = PyUnicode_AsUTF8(joined);
958 throwPythonException(env, messageStr);
965 *ty = (PyTypeObject *)exceptionType;
966 throwPythonException(
967 env, ty ? ty->tp_name
968 : "Internal error, null exception type");
971 Py_DECREF(formatExc);
974 throwPythonException(env, "Internal error, no format_exc function");
976 Py_DECREF(tracebackModule);
979 throwPythonException(env, "Internal error, no traceback module");
982 Py_XDECREF(exceptionType);
983 Py_XDECREF(exception);
984 Py_XDECREF(traceback);
988 (*env)->ReleaseStringUTFChars(env, statement, utfchars);
990 if (sclWriter != NULL) {
991 (*env)->CallVoidMethod(env, sclWriter, flushMethod);
997 return result != NULL ? 0 : 1;
1002 // Returns a borrowed reference.
1003 static PyObject *getPythonValue(
1004 JNIEnv *env, jlong contextID, jstring variableName) {
1005 PyObject *module = getModule(contextID);
1006 PyObject *pythonName = getPythonString(env, variableName);
1007 PyObject *value = PyDict_GetItem(PyModule_GetDict(module), pythonName);
1009 Py_DECREF(pythonName);
1010 if (value == NULL) {
1011 throwPythonException(env, "Python variable not found");
1016 #define DEF_GETTER(typename, jtype, check, desc, py2j) \
1017 JNIEXPORT jtype JNICALL \
1018 Java_org_simantics_pythonlink_PythonContext_getPython##typename \
1020 JNIEnv *env, jobject thisObj, jlong contextID, \
1021 jstring variableName) { \
1023 PyEval_RestoreThread(main_ts); \
1025 PyObject *value = getPythonValue(env, contextID, variableName); \
1026 if (value == 0) break; \
1027 if (check(value)) { \
1028 result = py2j(env, value); \
1030 throwPythonException(env, "Python variable not " desc); \
1033 PyEval_SaveThread(); \
1037 #define pythonBoolAsJboolean(env, value) ((value) == Py_True)
1038 #define pythonLongAsJlong(env, value) PyLong_AsLongLong(value)
1039 #define pythonFloatAsJdouble(env, value) PyFloat_AsDouble(value)
1041 DEF_GETTER(String, jstring, PyUnicode_Check, "a string",
1042 pythonStringAsJavaString)
1043 DEF_GETTER(StringArray, jobjectArray, PySequence_Check, "a sequence",
1044 pythonSequenceAsStringArray)
1045 DEF_GETTER(Boolean, jboolean, PyBool_Check, "a Boolean", pythonBoolAsJboolean)
1046 DEF_GETTER(BooleanArray, jbooleanArray, PySequence_Check, "a sequence",
1047 pythonSequenceAsBooleanArray)
1048 DEF_GETTER(Long, jlong, PyLong_Check, "an integer", pythonLongAsJlong)
1049 DEF_GETTER(IntegerArray, jintArray, PySequence_Check, "a sequence",
1050 pythonSequenceAsIntegerArray)
1051 DEF_GETTER(LongArray, jlongArray, PySequence_Check, "a sequence",
1052 pythonSequenceAsLongArray)
1053 DEF_GETTER(Double, jdouble, PyFloat_Check, "a float", pythonFloatAsJdouble)
1054 DEF_GETTER(DoubleArray, jdoubleArray, PySequence_Check, "a sequence",
1055 pythonSequenceAsDoubleArray)
1057 JNIEXPORT jobject JNICALL
1058 Java_org_simantics_pythonlink_PythonContext_getPythonNDArrayVariableImpl(
1059 JNIEnv *env, jobject thisObj, jlong contextID, jstring variableName) {
1060 jobject result = NULL;
1063 throwPythonException(env, "Importing numpy failed");
1067 PyEval_RestoreThread(main_ts);
1069 PyObject *value = getPythonValue(env, contextID, variableName);
1070 if (value == NULL) break;
1071 if (!PyArray_Check(value)) {
1072 throwPythonException(env, "Python variable not an ndarray");
1073 } else if (PyArray_TYPE((PyArrayObject*)value) != NPY_DOUBLE) {
1074 throwPythonException(
1075 env, "Only ndarrays of type double are supported");
1077 result = pythonArrayAsNDArray(env, (PyArrayObject *)value);
1080 PyEval_SaveThread();
1084 #define python_anything_goes(value) 1
1086 DEF_GETTER(Variant, jobject, python_anything_goes, "frabjous",
1087 pythonObjectAsObject)
1089 JNIEXPORT jint JNICALL
1090 Java_org_simantics_pythonlink_PythonContext_getPythonVariableTypeImpl(
1091 JNIEnv *env, jobject thisObj, jlong contextID, jstring variableName) {
1093 PyEval_RestoreThread(main_ts);
1095 PyObject *value = getPythonValue(env, contextID, variableName);
1096 if (PyBool_Check(value))
1098 else if (PyLong_Check(value))
1100 else if (PyFloat_Check(value))
1102 else if (PyUnicode_Check(value))
1104 else if (PyByteArray_Check(value))
1106 else if (PyDict_Check(value))
1108 else if (hasNumpy && PyArray_Check(value))
1110 else if (PySequence_Check(value))
1115 PyEval_SaveThread();
1119 JNIEXPORT jobjectArray JNICALL
1120 Java_org_simantics_pythonlink_PythonContext_getPythonVariableNamesImpl(
1121 JNIEnv *env, jobject thisObj, jlong contextID) {
1122 jobjectArray result = NULL;
1123 PyEval_RestoreThread(main_ts);
1125 PyObject *module = getModule(contextID);
1126 PyObject *dict = PyModule_GetDict(module);
1128 PyObject *keys = PyDict_Keys(dict);
1129 Py_ssize_t size = PyList_Size(keys);
1132 result = (*env)->NewObjectArray(
1133 env, (jsize)size, (*env)->FindClass(env, STRING_CLASS), NULL);
1135 for (i = 0; i < size; i++) {
1136 jstring javaName = pythonStringAsJavaString(
1137 env, PyList_GetItem(keys, i));
1138 (*env)->SetObjectArrayElement(env, result, (jint)i, javaName);
1143 PyEval_SaveThread();
1147 BOOL __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1148 //extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1152 case DLL_PROCESS_ATTACH:
1153 // attach to process
1154 // return FALSE to fail DLL load
1157 case DLL_PROCESS_DETACH:
1158 // detach from process
1161 case DLL_THREAD_ATTACH:
1165 case DLL_THREAD_DETACH:
1166 // detach from thread
1169 return TRUE; // succesful