+static JNIEnv *currentEnv = NULL;
+jobject sclWriter = NULL;
+
+static PyObject *
+writeToSCL(PyObject *self, PyObject *args)
+{
+ if (currentEnv != NULL && sclWriter != NULL) {
+ Py_UNICODE *what;
+ Py_ssize_t length;
+ JNIEnv *env = currentEnv;
+
+ if (!PyArg_ParseTuple(args, "u#", &what, &length))
+ Py_RETURN_NONE;
+
+ {
+ PyThreadState *my_ts = PyThreadState_Get();
+ if (my_ts == main_ts) {
+ jclass writerClass = (*env)->FindClass(env, WRITER_CLASS);
+ jmethodID writeMethod = (*env)->GetMethodID(env, writerClass, "write", "([CII)V");
+ jcharArray chars = (*env)->NewCharArray(env, (jsize)length);
+
+ (*env)->SetCharArrayRegion(env, chars, 0, length, what);
+ Py_BEGIN_ALLOW_THREADS
+ (*env)->CallVoidMethod(env, sclWriter, writeMethod, chars, 0, length);
+ Py_END_ALLOW_THREADS
+ } else {
+ //TODO
+ }
+ }
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+flushSCL(PyObject *self, PyObject *args)
+{
+ if (currentEnv != NULL && sclWriter != NULL) {
+ JNIEnv *env = currentEnv;
+ PyThreadState *my_ts = PyThreadState_Get();
+ if (my_ts != main_ts) {
+ // TODO: Process calls from other threads
+ Py_RETURN_NONE;
+ }
+
+ {
+ jclass writerClass = (*env)->FindClass(env, WRITER_CLASS);
+ jmethodID flushMethod = (*env)->GetMethodID(env, writerClass, "flush", "()V");
+
+ Py_BEGIN_ALLOW_THREADS
+ (*env)->CallVoidMethod(env, sclWriter, flushMethod);
+ Py_END_ALLOW_THREADS
+ }
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyMethodDef sclWriterMethods[] = {
+ {"write", writeToSCL, METH_VARARGS, "Write something."},
+ {"flush", flushSCL, METH_VARARGS, "Flush output."},
+ {NULL, NULL, 0, NULL}
+};
+
+JNIEXPORT void JNICALL
+Java_org_simantics_pythonlink_PythonContext_initializePython(
+ JNIEnv *env, jobject thisObj, jobject writer) {
+ Py_Initialize();
+
+ {
+ static struct PyModuleDef moduledef = {
+ PyModuleDef_HEAD_INIT, "sclwriter", NULL, -1, sclWriterMethods
+ };
+ PyObject *m = PyModule_Create(&moduledef);
+
+ sclWriter = (*env)->NewGlobalRef(env, writer);
+
+ if (m == NULL) {
+ throwException(env, PYTHON_EXCEPTION,
+ "Failed to create SCL writer module");
+ } else {
+ PySys_SetObject("stdout", m);
+ PySys_SetObject("stderr", m);
+ Py_DECREF(m);
+ }
+ }
+
+ hasNumpy = _import_array();
+ hasNumpy = hasNumpy != -1;
+
+ main_ts = PyEval_SaveThread();
+}
+